简体   繁体   中英

Set value in array PHP

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
        }
    }
}

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';
    }
}

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.

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