Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save conschneider/2bcccdfdce76e5f6b04d43b045b8be6c to your computer and use it in GitHub Desktop.
Save conschneider/2bcccdfdce76e5f6b04d43b045b8be6c to your computer and use it in GitHub Desktop.
Search through an array of objects by defined property value. Returns object.
<?php
$array = [
(object)['ID' => 420, 'name' => "Mary"],
(object)['ID' => 10957, 'name' => "Blah"],
];
$v=10957;
$entry = current(array_filter($array, function($e) use($v) { return $e->ID==$v; }));
echo "=== result ===\n\n";
print_r($entry);
echo "\n\n=== input ===\n\n";
print_r($array);
/*
Output:
=== result ===
stdClass Object
(
[ID] => 10957
[name] => Blah
)
=== input ===
Array
(
[0] => stdClass Object
(
[ID] => 420
[name] => Mary
)
[1] => stdClass Object
(
[ID] => 10957
[name] => Blah
)
)
Source: http://sandbox.onlinephpfunctions.com/code/332fb6032d8ea6129fa0af12aab35ea6aa32695d
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment