Reputation: 952
I'm trying to check if the of an id is available inside this array of std objects, i do not want to loop through the array as it will not display the correct information. My code is as follows:
Array( [0] => stdClass Object ( [name] => My Name [id] => 1234567890 ) [1] => stdClass Object ( [name] => Other User Name [id] => 987654321 ) )
I tried using in_array method and it doesnt find the id key and value.
Thank you D~~
Upvotes: 2
Views: 700
Reputation: 353
With the help of Anzeo's answer I upgraded it a bit to work with other properties and to be used in conditional statements, take a peek:
function my_in_array($needle, $haystack = array(), $property){
foreach ($haystack as $object) {
if($object->$property == $needle){
return true;
} else {
return false;
}
}
}
foreach($foo as $bar) {
if(!my_in_array($bar, $arrWithObjects, 'id')) {
//do something
}
}
Hope this is useful for someone else
EDITI also found a nice trick to convert the object's properties into an array, that might help in some situations.
foreach($arrWithObjects as $obj) {
$objProps = get_object_vars($obj);
if(in_array('My Name', $objProps)) {
//do something
}
}
Upvotes: 0
Reputation: 19738
You'll need to loop the array to perform a check on an attribute of the objects inside the array. Write a function that will return your desired value like (pseudo-code):
function returnObjectForId($idToMatch){
foreach ($array as $i => $object) {
if($object->id == $idToMatch){
return $object
}
}
}
Upvotes: 2