Tomáš Zato Tomáš Zato - 1 year ago 107
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:

$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
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
return $keys[$i];
else {
for($i=count($keys)-1; $i>=0; $i--) {
//benevolent search
return $keys[$i];

I'd prefer something better.

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

Reverse it first, then do your search

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download