-2

So lets say I have a multidimentional array as such

$myArray = [
    0 = [
        fruit = 'apple',
        juice = 'orange',
        cars = [bmw = 'blue', audi = 'red', ford = 'yellow']
    ],
    1 = [
        fruit = 'strawberry',
        juice = 'grape',
        cars = [bmw = 'grey', mazda = 'blue', hummer = 'orange']
    ],
]

and some replacement array values for cars

$replaceCarsArray = [ferrari = 'red', lamborghini = 'blue, masarati = 'pink']

I foreach through the array with $key => &$values (value being passed by reference)

foreach ($myArray as $key => &$values) {
    foreach ($values as $key2 => &$value) {
        if ($key2 == 'cars'){
            $value = $replaceCarsArray;
        }
    }
}

that works and replaces the entire cars values with the $replaceCarsArray

but what if I want to target one of the items in that cars array and change the color? So this is what I tried:

foreach ($myArray as $key => &$values) {
    foreach ($values as $key2 => &$value) {
        if ($key2 == 'cars' && $value['bmw'] != 'red'){
            $value['bmw'] = 'red';
        }
    }
}

this however does not seem to work and the bmw color does not get updated to red. How would I be able to change that data?

Note this is example data and I wrote it very quickly for all intents and purposes I do have access to all of the values and I do not have any syntactical errors in my code as might have appeared here.

Tyson
  • 13
  • 6

2 Answers2

0

Try the following

   $myArray[$key][$key2]['bmw'] = 'blue';
smavroud
  • 117
  • 4
  • yes that works but it is not changing the value by reference – Tyson Jan 09 '18 at 18:16
  • @user3896569 - If that works and gives you the same result, why does it matter if it's by reference or not? It's actually better to not use references in `foreach`-loops since it can lead to [strange and unwanted behavior](https://stackoverflow.com/questions/4969243/strange-behavior-of-foreach). – M. Eriksson Jan 09 '18 at 18:30
0

That worked for me

<?php

$myArray = [
    0 => [
        'fruit' => 'apple',
        'juice' => 'orange',
        'cars' => ['bmw' => 'blue', 'audi' => 'red', 'ford' => 'yellow']
    ],
    1 => [
        'fruit' => 'strawberry',
        'juice' => 'grape',
        'cars' => ['bmw' => 'grey', 'mazda' => 'blue', 'hummer' => 'orange']
    ]
];

echo "<pre>";
var_dump($myArray);
echo "</pre>";

foreach ($myArray as $key => &$values) {
    foreach ($values as $key2 => &$value) {
        if ($key2 == 'cars' && $value['bmw'] != 'red'){
            $value['bmw'] = 'red';
        }
    }
}

echo "<pre>";
var_dump($myArray);
echo "</pre>";

echo $myArray[0]['cars']['ford'];
echo $myArray[0]['cars']['bmw'];

tested on : http://phptester.net/

smavroud
  • 117
  • 4
  • lol you are correct I further tested even deeper multidimentional array and that worked too. – Tyson Jan 09 '18 at 18:56