Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

arrays

php

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.

like image 725
Tomáš Zato - Reinstate Monica Avatar asked Jan 19 '14 22:01

Tomáš Zato - Reinstate Monica


People also ask

What is Array_keys () used for?

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.

Is last in array PHP?

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.

How do you print the last element of an array in PHP?

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.

What is use of count () function in PHP?

The count() function returns the number of elements in an array.


2 Answers

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
like image 98
George Garchagudashvili Avatar answered Sep 30 '22 21:09

George Garchagudashvili


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

Reverse it first, then do your search

like image 23
Lee Avatar answered Sep 30 '22 20:09

Lee