1

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?

2 Answers 2

3

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

Sign up to request clarification or add additional context in comments.

2 Comments

Is there any better solution time complexity Big-O wise? I would need to place this in another loop, which will be a time complexity of O(n^2)
@GregoryR. using array_search may be faster. Other than that, you could build a hash of the PlaceId values and search using that...
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.