Tomáš Zato Tomáš Zato - 4 months ago 26
PHP Question

How do I find last occurence of "needle" in array php

There is a built in function for finding array key for a value -

. 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.

Lee Lee
Answer
array_search('green', array_reverse($array));

Reverse it first, then do your search

Comments