user3495336 user3495336 - 2 months ago 7
PHP Question

Array Combine Using String 'Keys' and Array 'Values'

I am attempting to use the array_combine function to combine a set of keys that are strings with a set of arrays. The array combine results in the new array being re-indexed.

$keys = array("00","11","22");
$values = array(0 => array("cake", "sprinkles"), 1 => array("dog", "cat"), 2 => array("water","fire"));

$combined_array = array_combine($keys, $values);


Result

Array
(
[0] => Array
(
[0] => cake
[1] => sprinkles
)

[1] => Array
(
[0] => dog
[1] => cat
)

[2] => Array
(
[0] => water
[1] => fire
)
)


Desired Result

Array
(
["00"] => Array
(
[0] => cake
[1] => sprinkles
)

["11"] => Array
(
[0] => dog
[1] => cat
)

["22"] => Array
(
[0] => water
[1] => fire
)
)

Answer

Your code is fine

only typo error $Keys instead of $keys

$combined_array = array_combine($keys, $values);

echo "<pre>";print_r($combined_array);

Output

Array
(
    [00] => Array
        (
            [0] => cake
            [1] => sprinkles
        )

    [11] => Array
        (
            [0] => dog
            [1] => cat
        )

    [22] => Array
        (
            [0] => water
            [1] => fire
        )

)

Also as commented how can you get output as you posted array_combine will through this error

Warning: array_combine() expects parameter 1 to be array, null given

Comments