Search code examples
phparraysforeachfiltering

Get the last occurring subarray containing a qualifying column value


In PHP they have non-integer indexes to access arrays. So you must iterate over an array using a foreach loop. This becomes problematic when you need to take some decision.

For example this array sample

"result": [
    {
      "timeStamp": "1622101761",
      "value": "468538",
    },
    {
      "timeStamp": "1622111811",
      "value": "3489422753882542",
    },
    {
      "timeStamp": "1622111814",
      "value": "468538",
    },
    {
      "timeStamp": "1622111816",
      "value": "28381635",
    }
]

I need to find the last array with condition value "468538" and must be the last item of array, how could I do this? Already create this code but no luck

  foreach ($array as $key => $value) {
      if (!next($array )) {
        if ($value['value']=="468538") {
          // last element with value 468538
          echo '<pre>';
          print_r($key);
          echo '</pre>';
          echo '<pre>';
          print_r($value);
          echo '</pre>';
        }
      } else {
          // not last element
      }
  }

but it show nothing, I need it to show it as a result

Array
(
    [timeStamp] => 1622111814
    [value] => 468538
)

Solution

  • The result array you're looping over is a numerically indexed array (JSON arrays are always indexed, JSON uses objects for associative arrays), so you don't have to worry about about non-numeric indexes.

    Use array_search(), array_column(), and array_reverse() to find the index of the last element of the array with value = 468538.

    Then when you're iterating over the array, you can check if this is the current index.

    $special_index = count($array) - array_search("468538", array_reverse(array_column($array, "value"))) - 1;
    
    foreach ($array as $i => $value) {
        if ($i === $special_index) {
            // do stuff for the special element
        } else {
            // do stuff for other elements
        }
    }