eman_invok05
eman_invok05

Reputation: 27

undefined offset PHP error in looping

it says an error undefined offset i dont know what causes it

im trying to shuffle $numberarray without repeating the number

heres the code

$numberarray = array(1,2,3,4,5,6,7,8,9,10);
for($counter=0;$counter<=9;$counter++)
        {
        $b = $counter - 1;
        $a = $numberarray[$counter];
            $numberarray[$counter] = rand(1,10);
            do
            {
                $numberarray[$counter] = rand(1,10);

                while($b != 0)
                {
                    if($numberarray[$counter] == $numberarray[$b])
                    {

                      $numberarray[$counter] = rand(1,10);
                      $b = $counter - 1;
                      //echo $b;
                    }
                    else
                    {
                      $b--;
                    }
            }

    }while($a == $numberarray[$counter]);
    echo $numberarray[$counter].", ";
}

sample output $numberarray = {3,4,5,1,2,7,9,10,8,5}

Upvotes: 0

Views: 79

Answers (2)

Adam Sinclair
Adam Sinclair

Reputation: 1649

This would be better:

(By the way you don't need an extra condition before the while since while act like a condition itself)

     $numberarray = array(1,2,3,4,5,6,7,8,9,10);
     for($counter=0;$counter<=9;$counter++)
        {
        $b = $counter - 1;
        $a = $numberarray[$counter];
            $numberarray[$counter] = rand(1,10);
            do
            {
              $numberarray[$counter] = rand(1,10);

             while($b >0)
             {
                if($numberarray[$counter] == $numberarray[$b])
                {

                    $numberarray[$counter] = rand(1,10);
                    $b = $counter - 1;
                    //echo $b;
                }
                else
                {
                    $b--;
                }
             }

        }while($a == $numberarray[$counter]);
        echo $numberarray[$counter].", ";
    }

Even if there is no more error, your code repeat numbers sometimes, so I would symply do it like this using shuffle:

      $numberarray2 = array(1,2,3,4,5,6,7,8,9,10);
      shuffle($numberarray2);
      print_r($numberarray2);

Upvotes: 1

Abdessabour Mtk
Abdessabour Mtk

Reputation: 3888

The problem is that in the first $b is equal to -1 that's why you get the error so i think you should delete the if condition and edit the while statement to while($b!=-1).

Upvotes: 0

Related Questions