3

I have an array like this:

Array
(
    [0] => name
    [1] => john
    [2] => last
    [3] => doe
    [4] => company
    [5] => sony
)

I need to convert to this:

Array
(
    [name] => john
    [last] => doe
    [company] => sony
)

Any ideas?

0

1 Answer 1

6
for ($i = 0; $i < count($myArray); $i += 2)
    $newArray[ $myArray[$i] ] = $myArray[$i+1];
Sign up to request clarification or add additional context in comments.

4 Comments

This will throw Notice: undefined offset if you have an array with an odd number of elements. Also count($myArray) will be calculated each loop, that will cause problems with bigger arrays
@kingkero Thanks for comment, you are right. I presumed array will be well formatted, in order not to complicate the answer.
@Martinsos I've an Array([0] => shiva [1] => kumar [2] => shrestha) and want to convert like Array([first_name] => shiva [middle_name] => kumar [last_name] => shrestha) What should I do for solving such problem?
@Martinsos I got my answer! $keys = array('first_name', 'middle_name', 'last_name'); $employee = array('shiva', 'kumar', 'shrestha'); $employee = array_combine($keys, $employee); Problem Resolved!

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.