Home > Back-end >  Access next array element value in PHP
Access next array element value in PHP

Time:07-24

I have this array

array:4 [
  0 => "B"
  1 => "C"
  2 => "D"
  3 => "A"
]

I want to traverse through this array

 for($i=0;$i<count($array);$i  )
      {
        if($i==0)
        {   
          $sequence_arr[]=$array[$i].''.$array[$i 1];
        }
        else
        { 
          $sequence_arr[]=$array[$i].''.$array[$i 1];
        }
      }

when i'm trying to access element from $array[$i 1] i get message

{message: "Undefined offset: 4", exception: "ErrorException

$array[$i] this is working but i want to access the next element of i.

Any Solution Thanks

CodePudding user response:

As there is no next element for the last element in the array, you should never access $array[$i 1] when $i == count($array) - 1.

Presumably you want to collect all pairs, but realise that the number of pairs is one less than there are elements in the array. So make your loop iterate one time less:

for ($i = 0; $i   1 < count($array); $i  )

NB: I don't see a difference in what is done for $i == 0 and the other cases.

  •  Tags:  
  • php
  • Related