Search code examples
phparraysfunctionfor-loopcycle

Why do I get undefined index while using simple array function


This is my example array:

$arrayy[0]=48.72;
$arrayy[1]=21.32;
$arrayy[2]=48.62;
$arrayy[3]=21.31;
$arrayy[4]=48.62;
$arrayy[5]=21.31;

This function

function writeDouble($array){
        for($curr = 0; $curr<count($array)-1; $curr++){
            echo $array[$curr]." - ";
            echo $array[$curr+1]."<br>";
            $curr++;
    }
}

should write a couples (0-1 , 2-3 , 4-5) - an output like:

48.72 - 21.32
48.62 - 21.31
48.62 - 21.31

What am I doing wrong, why do I got an error?

Notice: Undefined offset: 6 in C:\xampp\htdocs\xampp\lg\functions.php on line 466

Or could you define a better function to make couples? I can't think anymore... thanks


Solution

    1. You're using $array[$curr + 1] but you're iterating from 0 to $curr - 1. You need an isset in case you have an odd number of values in your array.

    2. You're incrementing 2 times (one time in your for, one time in the scope of your for).

    Code solution:

    $arrayy[0]=48.72;
    $arrayy[1]=21.32;
    $arrayy[2]=48.62;
    $arrayy[3]=21.31;
    $arrayy[4]=48.62;
    $arrayy[5]=21.31;    
    
    function writeDouble($array) {
            for ($curr = 0; $curr < (count($array) - 1); $curr += 2) {
                echo $array[$curr] . " - ";
                if (isset($array[$curr + 1])) {
                  echo $array[$curr + 1];
                }
                echo "<br>";
        }
    }
    
    writeDouble($arrayy);
    

    Output:

    48.72 - 21.32
    48.62 - 21.31
    48.62 - 21.31
    

    No more warning.