0

I am trying to search for an instance of a class in PHP but for the life of me I can't figure out how to do this, other than the obvious of recursing through each item in an array and checking the values. I was hoping someone can help if there is a way to do this. Here is an example

class Item {
    public $item;
    public $test;
    public function __construct($item) {
        $this->item = $item;
        $this->test = sprintf("%d - Hello", $item);
    }
}

$array = [];
for($i=0; $i < 100; $i++) {
    $array[] = new Item($i);
}

$foundItem = array_search(75, array_column($array, "item"));
echo print_r($foundItem, true);

I want $foundItem to be the entire object returned. Thanks in advance.

Barry
  • 3,303
  • 7
  • 23
  • 42

1 Answers1

0

array_search returns the key of the item in the array. Since you've still got your full array in scope, you can use this to access the entire object with a simple change:

$foundItem = $array[array_search(75, array_column($array, "item"))];

See https://3v4l.org/6k6nE (note that this needs PHP 7+, since array_column didn't work on an array of objects until then)

There are also a few other approaches you could use for this (although you said you wanted to avoid looping over the objects manually). array_column supports re-indexing an array by a given column using the third argument, so this would remove the need to use array_search:

$array = array_column($array, null, 'item');
$foundItem = $array[75];
iainn
  • 16,826
  • 9
  • 33
  • 40
  • Just tested this on php fiddle and it works fine. However, just tested on server and doesn't work as only has 5.3. DO you have any other ideas? Thanks – Phil Stather Aug 21 '18 at 19:25
  • Well my first thought would be to try and upgrade the server, but if that's not an option then there are ways of adding `array_column` support to earlier versions, [like this polyfill](https://github.com/ramsey/array_column) – iainn Aug 22 '18 at 08:14