简体   繁体   中英

Most efficient way to check if object value exists in PHP 7

I have the following object in PHP 7:

(int) 0 => object() {
   'master' => null
},
(int) 1 => object() {
   'master' => true
},
(int) 2 => object() {
   'master' => null
},

What is the most efficient way to check whether master is true in any key of that object?

I could loop through the object and then set a variable, eg

$master = 0;
foreach ($obj as $key => $value) {
    if ($value->master) {
       $master++;
    }
}
if ($master !== 0) {

}

But this seems inefficient.

The object itself has other data in each node, this is a simplified example.

What I'm trying to write, in as few lines as possible is, does any part of this object have master == true ? Or, looking at it the other way round, are all my master nodes set to null on this object? A return of true or false would probably suffice as the output, although a count would also be ok.

Assuming that you don't want to loop through the array, and the key of the "master" array is always "master", then this one-liner should do it:

$masterCount = count(array_filter(array_column($masterArray,'master')));

array_column is used to fetch all of the values of the "master" column, array_filter without a closure will automatically filter out empty values (false, null, 0) and count of the new array will get you the amount of true values.

if ($value->master && $value->master !== null) {
       $master++;
}

Have a look to this table : http://php.net/manual/en/types.comparisons.php

Use triple equal

if ($value->master === TRUE) {
   // your code here
}

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