Fixing a small mistake of the @YurkaTim, your solution work for me but adding use
:
To use $searchedValue
, inside of the function, one solution can be use ($searchedValue)
after function parameters function ($e) HERE
.
the array_filter
function only return on $neededObject
the if the condition on return is true
If $searchedValue
is a string or integer:
$searchedValue = 123456;
$neededObject = array_filter(
$arrayOfObjects,
function ($e) use ($searchedValue) {
return $e->id == $searchedValue;
}
);
var_dump($neededObject);
If $searchedValue
is array where we need check with a list:
$searchedValue = array( 1, 5 );
$neededObject = array_filter(
$arrayOfObjects,
function ( $e ) use ( $searchedValue ) {
return in_array( $e->term_id, $searchedValue );
}
);
var_dump($neededObject);