Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

{"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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading