Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save andres-mora-vanegas/b66c8c91c5593b7fd86d154dd022dc2d to your computer and use it in GitHub Desktop.

Select an option

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
<?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