Error comparing php array

Asked

Viewed 31 times

1

$rua[] = {1,1,2,2,2,2};

$countRua = count($rua, COUNT_RECURSIVE);

for ($i=0; $i < $countRua; $i++) { 
    if ($rua[$i] == $rua[$i+1]) {

    }
}

I own the for up through a array and validating if the position is equal to the next position however, when it arrives at the last it tries to compare with position 7 and returns the error below, some way to adjust it ?

Undefined offset: 6

  • It compares with the one in front can not go to the end

  • 1

    for the use of COUNT_RECURSIVE? can give a isset() in $rua[$i+1] that will tell whether index exists or not

  • Habito, could have used only Count even.

  • Go on until you get a wrong result :P

2 answers

1

Better start from the second item and each loop compare with the previous:

$rua[] = {1,1,2,2,2,2};

$countRua = count($rua, COUNT_RECURSIVE);

for ($i=1; $i < $countRua; $i++) { 
    if ($rua[$i] == $rua[$i-1]) {

    }
}

0


You can solve this by checking if the index exists with isset() the if condition should be composed in this way:

if (isset($rua[$i+1]) && $rua[$i] == $rua[$i+1]) {

Browser other questions tagged

You are not signed in. Login or sign up in order to post.