Search code examples
phparraysassociative-array

Comparing Next element inside foreach loop in associate array


I'm trying to access next key-value pair of associate array in php to check whether next key-value pair is same or not.

foreach($array as $key => $value){

    $b = $value['date'];
    $c = ($key+1)['date']; // As ($key+1) is integer value not an array

    if($b == $c){     
     statement        
    }
}

However, This approach is throwing below which seems to be logical.

ErrorException: Trying to access array offset on value of type int

Is there any way i could find next element inside foreach loop in associate array.

array (
  0 => 
  array (
    'date' => "2019-03-31",
    'a' => '1',
    'b' => '1',
  ),
  1 => 
  array (
    'date' => "2019-04-02",   
    'a' => '1',
    'b' => '1',
  ),
  2 => 
  array (
    'date' => "2019-04-02",  
    'a' => '2',
    'b' => '1',
  )
)

Solution

  • I don't know where you're getting $date you need 'date', and you're not using $array anywhere in the $c assignment. It can be shortened, but using your code, just check the next element:

    foreach($array as $value) {
        $b = $value['date'];
        $c = next($array)['date'] ?? false;
        
        if($b == $c) {     
            echo 'Yes';
        }
    }
    

    If they are sequential integer keys then you can do it your way, just check that $key+1 is set:

    foreach($array as $key => $value) {
        $b = $value['date'];
        $c = $array[$key+1]['date'] ?? false;
        
        if($b == $c) {     
            echo 'Yes';
        }
    }