0

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')

3 Answers 3

2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

PHP will handle type casting anyway. So $arr['1'] and $arr[1] can be considered the same unless a strict equality sign === is used.
Yes, I know; but why would you want to degrade performance (however little) to do something that is unneeded?
Totally agreed. You will need to use a loop to convert those into integers, though, which I would personally do anyway :)
1

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);

Comments

0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.