Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
579 views
in Technique[技术] by (71.8m points)

php - 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',
  )
)
question from:https://stackoverflow.com/questions/66067739/comparing-next-element-inside-foreach-loop-in-associate-array

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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';
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...