Search code examples
phparraysfilteringassociative-array

Filter associative array to keep elements when their value is greater than their neighboring elements' values


I have an associative array from which I need a new array to be created. I am targeting the peak values for the new array. For a value to be selected to the new array, it needs to be higher than both the previous and the next value in the array.

I have searched the net and found a function that could handle the situation for indexed arrays - but not for associative arrays. Here is what I would like:

$array = array('a' => 0, 'b' => 2, 'c' => 1, 'd' => 2, 'e' => 3);
$result = array('b' => 2, 'e' => 3);

The function usable for indexed arrays look like this:

$a = array(0, 2, 1, 2, 3);
$b = array_filter($a, function($v, $k) use($a) {
  return $k > 0 && $v > $a[$k-1] && $k + 1 < count($a) && $v > $a[$k+1];
}, ARRAY_FILTER_USE_BOTH );

This function doesn't include the last value either.


Solution

  • You should change the condition if you really want to get border items. But an approach could be to use the array of keys to get prev and next items

    $array = array('a' => 0, 'b' => 2, 'c' => 1, 'd' => 2, 'e' => 3);
    $keys = array_keys($array);
    
    $b = array_filter($array, function($v, $k) use($array, $keys) {
      $k = array_search($k, $keys);
      return $k > 0 && $v > $array[$keys[$k-1]] && $k + 1 < count($keys) && $v > $array[$keys[$k+1]];
    }, ARRAY_FILTER_USE_BOTH );
    
    print_r($b);