Reputation: 40289
I am trying to find a value in array by searching on a different column value.
This is my array:
Array
(
[0] => Array
(
[triggerOn] => 07/19/2013 04:32 PM
[isAppointment] => 0
[engine_id] => 112
)
[1] => Array
(
[triggerOn] => 07/26/2013 04:32 PM
[isAppointment] => 1
[engine_id] => 111
)
)
I am trying to find the value of triggerOn
when engine_id
equals 111
?
So if I have the value 111
then I need to return 07/26/2013 04:32 PM
.
If I have the value 112
, then I need to return 07/19/2013 04:32 PM
.
How can I do this?
This is what I have tried so far:
function returnValueOfArray($arr, $val) {
foreach ($arr as $v) {
foreach ($v as $sub) {
if ($val == $sub)
return $v['triggerOn'];
}
}
return 'Nothing Found';
}
but this is not working.
Upvotes: 0
Views: 63
Reputation: 47864
As of PHP8.4, developers are no longer confined to manually writing a conditionally broken loop to search array multidimensional array. array_find()
allows the efficiency of conditionally broken array traversal with a native function.
If the qualifying condition is never satisfied, null
is returned. Attempt to access the desired element in the returned value; if it cannot be accessed, then default to whatever value you like. Demo
$engineId = 111;
var_export(
array_find(
$array,
fn($row) => $row['engine_id'] == $engineId
)['triggerOn'] ?? 'Nothing Found'
);
Upvotes: 0
Reputation: 5428
another way to do is :
// let's assume your array is called $myArray
for($i=0; $i < count($myArray) ; $i++ ){
if($myArray[$i]['engine_id'] == '111'){
return $myArray[$i]['triggerOn'];
break;
}
}
in a function it gives this :
function find_engine($engine, $myArray){
for($i=0; $i < count($myArray) ; $i++ ){
if($myArray[$i]['engine_id'] == $engine){
return $myArray[$i]['triggerOn'];
break;
}
}
}
Upvotes: 0
Reputation:
function search_in_array($array, $engine_id){
foreach($array as $key => $val){
if($engine_id == $val['engine_id']){
return $val['triggerOn'];
}
}
}
Upvotes: 1
Reputation: 18550
function findEngine_id($engine, $array){
foreach($array as $item){
if($item['engine_id'] == $engine) return $item['triggerOn'];
}
return false;
}
echo findEngine_id(111,$array);
Upvotes: 3