santa
santa

Reputation: 12512

Getting a value from an array in PHP

I'm a bit confused with the array that I have to work with. The following array:

print_r($myArray);

returns the following:

Array (
    [0] => stdClass Object (
        [id] => 88
        [label] => Bus
    )
    [1] => stdClass Object (
        [id] => 89
        [label] => Bike
    )
    [2] => stdClass Object (
        [id] => 90
        [label] => Plane
    )
    [3] => stdClass Object (
        [id] => 91
        [label] => Submaine
    )
    [4] => stdClass Object (
        [id] => 92
        [label] => Boat
    )
    [5] => stdClass Object (
        [id] => 93
        [label] => Car
    )
    [6] => stdClass Object (
        [id] => 94
        [label] => Truck
    )
) 

How do I get the label value, say, "Submaine", if I have the $id = 91?

Upvotes: 2

Views: 302

Answers (3)

lonesomeday
lonesomeday

Reputation: 238075

You're going to have to loop through the array, I think.

$value = '';
foreach ($myArray as $el) {
    if ($el->id === 91) { // or other number
        $value = $el->label;
        break;
    }
}

The label is now contained in $value.


Benchmark values vs AJ's version for 1000000 iterations (see source):

lonesomeday: 1.8717081546783s
AJ: 4.0924150943756s
James C: 2.9421799182892s

Upvotes: 3

James C
James C

Reputation: 14169

What you have there is an array of objects. I'd suggest re-keying the array by id like this:

$new = array();
foreach($array as $obj) {
    $new[ $obj->id ] = $new[ $obj->label ];
}

Now you've got a nice associative array that you can use normally e.g. echo $new[92] will echo "Boat"

Upvotes: 2

AJ.
AJ.

Reputation: 28194

This will get you the object(s) you seek:

$objects = array_filter($myArray, function($item){ return $item->id == 91 })

Then it's just a matter of getting the attribute of the object that you want.

Upvotes: 7

Related Questions