Search code examples
phparraysobject

Check if object with property = value exists in array of objects


I think I could do this with a foreach loop like this:

 foreach ($haystack as $item)
       if (isset($item->$needle_field) && $item->$needle_field == $needle)
            return true;
 } 

but i was wandering if it could be done without a loop?

something like:

  if(in_array($item->$needle_field == $needle,$haystack)
            return true;

Solution

  • It's possible, but it's not any better:

    <?php
    function make_subject($count, $success) {
        $ret = array();
        for ($i = 0; $i < $count; $i++) {
            $object = new stdClass();
            $object->foo = $success ? $i : null;
            $ret[] = $object;
        }
        return $ret;
    }
    
    // Change true to false for failed test.
    $subject = make_subject(10, true);
    
    if (sizeof(array_filter($subject, function($value) {
        return $value->foo === 3;
    }))) {
        echo 'Value 3 was found!';
    } else {
        echo 'Value 3 was not found.';
    }
    

    Outputs Value 3 was found!.

    I advise you remain with the for loop: it's legible, unlike any tricks to save a line that you might find.