How can I set one array as a value of another array in PHP?

I have the following array:

Array
(
    [0] => James
    [1] => Mike
    [2] => Liam
    [3] => Shantel
    [4] => Harry
)
Array
(
    [0] => Green
    [1] => Blue
    [2] => Yellow
    [3] => Purple
    [4] => Red
)

How can I get these two arrays into a JSON object?

So this should be the expected output:

{"James":"Green","Mike":"Blue","Liam":"Yellow","Shantel":"Purple"}

This is what I tried doing but I’m getting a totally different output:

$final = array();
$names = ['James', 'Mike', 'Liam', 'Shantel', 'Harry']
$colors = ['Green', 'Blue', 'Yellow', 'Purple', 'Red']


for ($i = 0; $i <= 4; $i++) {
    $final[] = array_push($final, $names[$i], $colors[$i]);
}

What am I doing wrong here?

>Solution :

You want to set a specific key of $final to a specific value. So instead of using array_push (or $final[]), which just adds a value to an indexed array, you want to define the key/value of the associated array $final like:

$final[$names[$i]] = $colors[$i];
$final = array();
$names = ['James', 'Mike', 'Liam', 'Shantel', 'Harry'];
$colors = ['Green', 'Blue', 'Yellow', 'Purple', 'Red'];


foreach($names as $i => $key) {
    $final[$key] = $colors[$i];
}

Working example at https://3v4l.org/cgHtD

Leave a Reply