Created
August 15, 2019 14:07
-
-
Save conschneider/2bcccdfdce76e5f6b04d43b045b8be6c to your computer and use it in GitHub Desktop.
Search through an array of objects by defined property value. Returns object.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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