简体   繁体   中英

Adding elements to an array using key/value in PHP?

I know I can add elemnts to an array like this:

$arr = array("foo" => "bar", 12 => true);

Now, how can I do that in a foreach using dynamic values? I have this code:

foreach ($values as $value) {

    $imagePath = $value->getImagePath();
    $dependsOn = $value->getDependsOn();
    $dependsOn = explode(':', $dependsOn);
    $dependsOnOptionValueTitle = trim($dependsOn[1]);

    array_push($paths, $dependsOnOptionValueTitle => $imagePath); // not working
}

How can I add key/value pairs to my $paths array?

Instead of

array_push($paths, $dependsOnOptionValueTitle => $imagePath); // not working

you should be able to use

$paths[$dependsOnOptionValueTitle] = $imagePath;

From what I can see, this is what you're trying to do:

$paths[$dependsOnOptionValueTitle] = $imagePath;

Comment if I'm wrong and I'll try to fix it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM