0

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?

4
  • Try a foreach loop instead : php.net/manual/en/control-structures.foreach.php Commented Jun 12, 2015 at 13:42
  • 1
    while( isset($data[$i]) ) { The condition needs to be boolean TRUE or FALSE. Though you'd be best to use a foreach loop to traverse through an array. Commented Jun 12, 2015 at 13:46
  • What???? I don't understand what you are doing here... you are adding the whole array $data2 to the end of $data while there is a value in $data that sounds non-sense to me...? Commented Jun 12, 2015 at 13:47
  • @JuniusRendel I know this code is confusing. I am still trying to figure out what was in developer's mind when he wrote this code. Commented Jun 12, 2015 at 13:55

1 Answer 1

7

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])){}
Sign up to request clarification or add additional context in comments.

2 Comments

Note: Using isset in the while condition because the condition needs to equate to boolean TRUE/FALSE; which isset will do (also handling the undefined offset).
Thanks Richard Reiber and @ʰᵈˑ

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.