I have an array $arr looking like this:
array(3) {
[0]=>
array(2) {
["food"]=>
string(5) "Toast"
["age"]=>
string(2) "28"
}
[1]=>
array(2) {
["food"]=>
string(5) "Pizza"
["age"]=>
string(2) "45"
}
[2]=>
array(2) {
["food"]=>
string(5) "Steak"
["age"]=>
string(2) "33"
}
}
I also have a variable $curr_age = 45;.
Now I am looking for a way to search through the array until I find $arr[$i]["age"] = $curr_age and then stop.
Also, how do I get the food from the next & previous arrays (Toast and Steak in the example)?
For searching through the array, I have this code:
$i = 0;
foreach( $arr as $array ){
if( $curr_age == $arr[$i]["age"] ) {
$next = $arr[$i++]["food"];
$prev = $arr[$i--]["food"];
}
$i++;
}
As you can probably imagine, this is not working as expected and I have no idea why. One thing that strikes me though is the fact that the foreach loop is actually only used to increment $i and that $array is never used, but I can’t get my head around how to fix this or how to perform the task mentioned above in general.
I think I already found out that there is no “built in” way in PHP to do this, an extra function is needed, but again: I have no clue what that function needs to do. I am not even sure if this statement is true.
I already tried array_search and then simply increment/decrement the key by 1, but that didn’t work for two reasons I believe. First it seems that array_search can’t handle that type of array & second, the keys can be non-consecutive, so doing $x++ or $x-- doesn’t seem right.
Your array indexes are already numeric so there’s not really a need to also maintain an incrementing index, just use the key assignment in the foreach loop, and make sure you test the previous and next keys actually exist before trying to access them