-1

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

user1666761
  • 163
  • 2
  • 3
  • 13

3 Answers3

4

Because in the last iteration in line echo $array[$curr+1]."<br>"; you'll be looking for $array[count($array)] which is ofcource not defined!!

Rajat Singhal
  • 11,234
  • 5
  • 38
  • 56
0
  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.

Kenny Linsky
  • 1,726
  • 3
  • 17
  • 41
Alain Tiemblo
  • 36,099
  • 17
  • 121
  • 153
0

Note that you are incrementing $curr two times:

for($curr = 0; $curr<count($array)-1; $curr++){

and

$curr++

This is the reason for going out of range in your loop

Hernan Velasquez
  • 2,770
  • 14
  • 21