3

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
        }
    }
}
2
  • How does your array structure looks like? What is the problem? Commented Apr 16, 2015 at 12:05
  • 3
    Have you tried $obj['color'] = 'blue'; Commented Apr 16, 2015 at 12:05

2 Answers 2

4

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';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.