Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a value from an array in PHP

Tags:

arrays

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?

like image 768
santa Avatar asked Dec 07 '25 12:12

santa


2 Answers

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.

like image 182
AJ. Avatar answered Dec 10 '25 01:12

AJ.


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
like image 37
lonesomeday Avatar answered Dec 10 '25 02:12

lonesomeday