Peter
Peter

Reputation: 111

PHP While loop Notice: Undefined offset

I am fixing an existing PHP code

I get error

Notice: Undefined offset: 6

The PHP code will look like below. It is a big while loop. Here I just show the main section.

$data = Array
(
    [0] => 1
)

$data2 = Array
(
    [0] => 1
    [1] => 10
    [2] => 12
    [3] => 15
    [4] => 17
    [5] => 23
)


$i = 0;
while($data[$i]){
    array_push($data,$data2);
    $i++;
}

Also,

Sometimes, I get error

Notice: Undefined offset: 4

for

$data2 = Array
(
    [0] => 12
    [1] => 34
    [2] => 56
    [3] => 78
    [4] => 83
)

How do I fix this issue?

Upvotes: 0

Views: 2059

Answers (1)

Richard
Richard

Reputation: 2815

You should use foreach for iterating through arrays:

foreach($data as $key => $value) {}

Your warning with while is that you do check if this array position exists right. Use this instead:

while(isset($data[$i])){}

Upvotes: 7

Related Questions