PHP Error with array

0

Why this php error Notice: Undefined offset: 58

Skip that error when using the following function, more specifically on the line marked with the comment.

<?php

    public function repeatLine($string){
        $array = str_split($string);
        for($i=0;$i<count($array);$i++){
            if($array[$i] == "-" && $array[$i+1] == "-"){ ///////Acá salta el error!
                $array[$i+1] = "";
            }
        }
        return $array;
    }

?>
    
asked by Camilo 21.03.2018 в 22:07
source

1 answer

1

This happens because in the last iteration of the cycle, you are trying to access an index that does not exist in the array.

That is given in the line you mark because there you are placing $i+1 , and that, in practice means that if the position of the iteration is 0, you agree to position 1, and so on, until the end. But precisely at the end, when you have reached the last iteration of the cycle, when $i equals count()-1 , you want to access the position equal to count() , which in PHP can not be accessed: remember that arrangements in PHP start at base 0, so if the array has 7 elements, the last index will be 6. Then, when you try to enter position 7, that error jumps.

    
answered by 21.03.2018 / 22:12
source