Gregory R.
Gregory R.

Reputation: 1935

Find object by value in array of objects in PHP

I have an array of objects in PHP, like so:

[Places] => Array
    (
        [0] => stdClass Object
            (
                [PlaceId] => 837
                [Name] => United Arab Emirates
                [Type] => Country
            )

        [1] => stdClass Object
            (
                [PlaceId] => 838
                [Name] => Afghanistan
                [Type] => Country
            )

        [2] => stdClass Object
            (
                [PlaceId] => 839
                [Name] => Antigua and Barbuda
                [Type] => Country
            )
    )

How can I retrieve the Object inside this array if I only know the value of PlaceId, such as 837?

Upvotes: 0

Views: 1835

Answers (2)

A l w a y s S u n n y
A l w a y s S u n n y

Reputation: 38502

With array_search and array_column(),

$key = array_search(839, array_column($places['Places'], 'PlaceId'));
print_r($places['Places'][$key]);

Output:

stdClass Object ( 
  [PlaceId] => 839 
  [Name] => Canada 
  [Type] => Country
 )

DEMO: https://3v4l.org/RsPr4

Upvotes: 0

Nick
Nick

Reputation: 147166

A simple foreach loop will do the job:

foreach ($places as $place) {
    if ($place->PlaceId == 837) break;
}
if ($place->PlaceId == 837) 
    print_r($place);
else
    echo "Not found!";

Output:

stdClass Object
    (
         [PlaceId] => 837
         [Name] => United Arab Emirates
         [Type] => Country
    )

Demo on 3v4l.org

It may be faster to use array_search on the PlaceId values, which you can access using array_column:

if (($k = array_search(837, array_column($places, 'PlaceId'))) !== false) {
    print_r($places[$k]);
}
else {
    echo "Not found!";
}

Demo on 3v4l.org

Upvotes: 2

Related Questions