Reputation: 15270
How do you recommend fetching the key of the last matching value in an array?
$arr = array(
0 => 0,
1 => 1,
2 => 2,
3 => 3,
4 => 4,
5 => 5,
6 => 5,
7 => 5,
8 => 5,
9 => 5, // <--- this is the key I'm after!
10 => 6,
11 => 7,
12 => 8,
13 => 9,
14 => 10,
15 => 11);
function returnLastMatching($haystack,$needle) {
// return 9
}
echo returnLastMatching($arr,5); // "9"
Upvotes: 1
Views: 913
Reputation: 11293
Try the following:
$last_key = -1;
$foreach ($haystack as $key => $value) {
if ($value == $needle) {
$last_key = $key;
}
}
Each time the value = the needle it will overwrite the last element and save the key, in the end you will have the last occurrence.
== As Bora suggested ==
function returnLastMatching($haystack,$needle) {
return array_pop(array_keys($haystack, $needle));
}
Upvotes: 2
Reputation: 52
This should probably work:
function returnLastMatching($haystack,$needle) {
foreach($haystack as $key=>$element)
{
if($element==$needle)
{
$temp=$key;
}
}
return $temp;
}
Upvotes: 0
Reputation: 8334
This solution using array_search()
and array_reverse()
, you first reverse your array and then take the first key that matchs your needle:
function returnLastMatching($haystack,$needle) {
return array_search($needle,array_reverse($haystack, true));
}
Use array_keys()
to get all keys that match your needle , and then get the last element from this array of keys:
function returnLastMatching($haystack,$needle) {
return end(array_keys( $haystack, $needle));
}
Upvotes: 1
Reputation: 3218
change echo returnLastMatching($arr,5);
with
$arr = array_flip($arr);
echo $arr[5];
No need to use function we can get the result
Upvotes: 0
Reputation: 9646
You can use array_keys
$keys = array_keys($arr, 5); //will return all matched keys
echo end($keys); //will output the last key it was matched with
Upvotes: 1
Reputation: 6830
The foreach construct has 2 possible signatures, one of which will also give you the key value of the current element:
function returnLastMatching($haystack,$needle) {
foreach (array_reverse($haystack) as $k => $val)
if ($val == $needle) return $k;
// instead of
// foreach ($haystack as $val)...
}
To get the last element, the array_reverse
call is added while passing the array to foreach.
Upvotes: 1
Reputation: 3655
$lastkey = false;
foreach($haystick as $key => $val) {
if($val === $needle) $lastkey = $key;
}
return $lastkey;
This will iterate to the end of the haystick, thus returning the last key if there is at least one, or false if there is none.
Upvotes: 1
Reputation: 3054
function returnLastMatching($haystack,$needle) {
return array_pop(array_keys($haystack, $needle));
}
Upvotes: 1
Reputation: 10717
Try this one with array_pop
and array_keys
function returnLastMatching($haystack,$needle) {
return array_pop(array_keys($haystack, $needle));
}
array (size=5)
0 => int 5
1 => int 6
2 => int 7
3 => int 8
4 => int 9
9
Upvotes: 2