There is a built in function for finding array key for a value - array_search
. However as you can see from the example, the function only finds first occurrence, whereas I need the last one:
<?php
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$key = array_search('green', $array); // $key = 2;
$key = array_search('red', $array); // $key = 1;
?>
Is there any built in function for this?
If not, can I make a foreach
go backwards (from last key to the first one)?
If all the answers are no, I guess this is the only solution:
function array_search_last($needle, $array, $strict = false) {
$keys = array_keys($array);
//Not sure how smart PHP is, so I'm trying to avoid IF for every iteration
if($strict) {
for($i=count($keys)-1; $i>=0; $i--) {
//strict search
if($array[$keys[$i]]===$needle)
return $keys[$i];
}
}
else {
for($i=count($keys)-1; $i>=0; $i--) {
//benevolent search
if($array[$keys[$i]]==$needle)
return $keys[$i];
}
}
}
I'd prefer something better.
The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.
The end() function is an inbuilt function in PHP and is used to find the last element of the given array. The end() function changes the internal pointer of an array to point to the last element and returns the value of the last element.
The end() function moves the internal pointer to, and outputs, the last element in the array. Related methods: current() - returns the value of the current element in an array.
The count() function returns the number of elements in an array.
But all of them missed one thing, that would cause incorrect results for OP's need, he is seeking for index of last element and reversing array will cause to reindex keys (when numeric), so final solution is to set preserve_keys
param to TRUE
see docs:
$array = array(0 => 'blue', 1 => 'red', 2 => 'green', 3 => 'red');
$reversed = array_reverse($array, true);
echo array_search('red', $reversed);
// outs 3
array_search('green', array_reverse($array));
Reverse it first, then do your search
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With