Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Access next array element value in PHP

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

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

Any Solution Thanks

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading