skip to Main Content

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
)

Any help would be nice

2

Answers


  1. Here is one approach to solve it. This is bringing in your data as an array named $haystack and you provide a value for $needle. I’m outputting it as JSON and letting PHP handle the formatting since hand formatting as you have done in your example probably isn’t what you really need. This also includes a check just in case you’re looking for a value that does not exist.

    $needle = "468538";
    $needleLocation = -1;
    
    for ($i = 0; $i < count($haystack); $i++) {
        if($haystack[$i]['value']==$needle) $needleLocation=$i;
    
    }
    
    if($needleLocation != -1){
        echo json_encode($haystack[$needleLocation]);
    }
    else{
        echo $needle . " is not found in the haystack";
    }
    

    Gives a result of:

    {"timeStamp":"1622111814","value":"468538"}
    
    Login or Signup to reply.
  2. Because you will need to iterate the full array to be sure you are accessing the latest occurrence, you might enjoy a functional-style iterator.

    Use array_column() to assign new first level keys. This will overwrite earlier keyed rows with later keyed rows, then you can merely access the sought row values by the new key. If it doesn’t exist in the new array, fall back to null.

    Code: (Demo)

    var_export(
        array_column($array['result'], null, 'value')[468538] ?? null
    );
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search