0

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',
  )
)
2
  • 1
    ($key+1) is an integer value, so ($key+1)['date'] will complain. Try $array[$key + 1][$date] and be careful for the last iteration. Commented Feb 5, 2021 at 17:26
  • Exactly, So How do i compare the? Commented Feb 5, 2021 at 17:27

1 Answer 1

1

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';
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.