Created
March 15, 2023 18:42
-
-
Save andres-mora-vanegas/b66c8c91c5593b7fd86d154dd022dc2d to your computer and use it in GitHub Desktop.
This code is used to return the first element in an array of elements passing the key, the value and the array
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 | |
$arr=[]; | |
$obj1 = new StdClass(); | |
$obj1->name="juan"; | |
$obj1->id="321"; | |
$obj1->phone="111111"; | |
$obj2 = new StdClass(); | |
$obj2->name="pedro"; | |
$obj2->id="123"; | |
$obj2->phone="333333"; | |
$obj3 = new StdClass(); | |
$obj3->name="ana"; | |
$obj3->id="321"; | |
$obj3->phone="444444"; | |
array_push($arr,$obj1); | |
array_push($arr,$obj2); | |
array_push($arr,$obj3); | |
function findObjectByKey($key, $value, $array) | |
{ | |
$result = array_filter($array, function ($elem) use ($key, $value) { | |
return $elem->{$key} == $value; | |
}); | |
if (count($result) > 0) { | |
return $result[key($result)]; | |
} | |
return false; | |
} | |
$result = findObjectByKey("id","321",$arr); | |
var_dump($result); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment