0

Is there a simpler than:

foreach ($array as $key => $value) {
    if($value['date']->ID == 22) { echo $key; }
}

for searching for ID->22 (each ID is unique) and then if it exists, return the parent key? In this case it would be key 0:

Array
(
    [0] => Array
        (
            [date] => WP_Post Object
                (
                    [ID] => 22                    
                )

        )
    [1] => Array
        (
            [date] => WP_Post Object
                (
                    [ID] => 33                    
                )

        )

)

Just curious if there is a less intensive way of doing this as it will have to be done a lot on any given page. If not, is it practical to run 700 of these loops at once?

deflime
  • 603
  • 1
  • 9
  • 17

1 Answers1

1

This answer doesn't address the Is there a simpler than: part of this question. The foreach loop is more than likely the simplest way to do this. I am taking your question at the bottom of the answer is [there] a less intensive way of doing this as the real question.

As has been mentioned in comments you can use break to get out of the loop when you have a result, stopping any further unnecessary processing.

foreach($array as $key => $value)
{
    if ($value->ID === 22)
    {
        echo $value->ID;
        break;
    }
}

Having your results sorted can also have a major impact on the performance of a loop like this. When you introduce conditional logic your processor tries to predict the result of the statement before it knows what the actual value of $value->ID is. If you allow it the means to predict this, you can make the loops much faster. This is called branch prediction. There is an excellent answer on SO about this here that will help you.

Community
  • 1
  • 1
David Barker
  • 14,484
  • 3
  • 48
  • 77