Reputation: 65
I have an multidimensional array with objects. If the object has status 1 or 2 and the color is not green, I want to set color to blue. How can I do that?
foreach ($objects as $obj) {
if (in_array($obj['status'], [1,2] )) {
if ($obj['color'] != 'green'){
//set color to blue
}
}
}
Upvotes: 3
Views: 20241
Reputation: 6666
The answer provided by @Ghost is correct when working with arrays. As arrays are not really objects they must be passed by reference otherwise they are copied. Objects are passed by reference.
This is actually pretty horrible, and one of the (many) reasons you should avoid basic PHP arrays. Additionally, if you make a reference of a reference, you'll likely end up with a memory leak.
If $objects
where actually an array of actual objects, you don't need to specify that it should be treated as an exception. Here's a test I wrote (sorry it's a bit ugly):
$objects = array(
(object)array(
'status' => 1,
'color' => 'red',
)
);
foreach ($objects as $obj) {
if (in_array($obj->status, array(1,2)) && $obj->color != 'green') {
// set to blue
$obj->color = 'blue';
}
}
foreach ($objects as $obj) {
echo $obj->color;
}
For the most part, PHP objects are faster and more memory efficient that PHP arrays, and will act very similarly in most cases.
Upvotes: 2
Reputation: 41885
No need to have nested ifs, just combine them into one condition, and you can reference the copy &
to make your changes:
foreach ($objects as &$obj) {
// ^ reference
if (in_array($obj['status'], [1,2]) && $obj['color'] != 'green') {
// set to blue
$obj['color'] = 'blue';
}
}
Upvotes: 4