Reputation: 200
I have a sample code:
$id = '1,2,3,4,5';
$name = 'Iphone 3,Iphone 3S,Iphone 4,Iphone 4S,Iphone 5';
$id_arr = array($id);
$name_arr = array($name);
$arr = array_combine($id_arr, $name_arr);
print_r($arr);
When I print_r($arr)
is result is ([1,2,3,4,5] =>'Iphone 3,Iphone 3S,Iphone 4,Iphone 4S,Iphone 5')
How to fix this is the result ([1]=>'Iphone 3' [2] => 'Iphone 3S' ... [5]=>'Iphone 5')
Upvotes: 0
Views: 58
Reputation: 6088
I'm not sure why you have to start your array with 1 but if you want to maintain such order and keep keys as integers it can be done like this:
$name = 'Iphone 3,Iphone 3S,Iphone 4,Iphone 4S,Iphone 5';
$parts = explode(',', $name);
$arr = array();
$i = 1;
foreach($parts as $value)
{
$arr[$i] = $value;//we can possibly strip leading spaces and convert string case
$i++;
}
print_r($arr);
Upvotes: 0
Reputation: 446
or try :
$id = '1,2,3,4,5';
$name = 'Iphone 3,Iphone 3S,Iphone 4,Iphone 4S,Iphone 5';
$id_arr = explode(',',$id);
$name_arr =explode(',',$name);
$arr = array_combine($id_arr, $name_arr);
print_r($arr);
Upvotes: 1
Reputation: 11122
The correct function to use given that input is explode
. str_split
has unneeded overhead.
$id_arr = explode(',', $id);
.
Note that arrays should actually be defined like so: $id_arr = array(1 => 'value 1', 2 => 'value 2', 3 => 'value 3');
etc... unless you are forced to use a string as the key set.
Upvotes: 2