PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, May 16, 2022

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

 May 16, 2022     arrays, list, php, string     No comments   

Issue

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



Answered By - WOUNDEDStevenJones
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing