-1
<?php 
        $luckyNumbers = array (4,5,6,1,2,34);
        
        for($i=0; $i <= count($luckyNumbers); $i++){
            echo "$luckyNumbers[$i] <br>";
        }                 
?>

I was trying to output

4
5
6
1
2
34

But the warning below is appearing - I just use the asterisk to cover folder name.

Warning: Undefined array key 6 in C:\Users******\php project\index.php on line 315

So the output becomes like this.

4
5
6
1
2
34

Warning: Undefined array key 6 in C:\Users\******\php project\index.php on line 315

Why is the error appearing when the output is right?

ADyson
  • 57,178
  • 14
  • 51
  • 63
Nino Sun
  • 3
  • 1
  • This is the code I used: "; } ?> – Nino Sun Jul 23 '23 at 21:34
  • Because your array has six elements whose indexes start at 0. 5 is therefore the last index. Looping number 6 is the problem because it doesn't exist - as the message is telling you, index 6 is not defined – ADyson Jul 23 '23 at 21:35
  • 1
    Use `print_r($luckyNumbers);` to see the structure and indexes. Use `i < count($luckyNumbers);` to fix the bug (note `<` instead of `<=`) – ADyson Jul 23 '23 at 21:37
  • 1
    ["Notice: Undefined variable", "Notice: Undefined index", "Warning: Undefined array key", and "Notice: Undefined offset" using PHP](https://stackoverflow.com/questions/4261133/notice-undefined-variable-notice-undefined-index-warning-undefined-arr) – ADyson Jul 23 '23 at 21:48

1 Answers1

0

Use foreach instead

<?php 
        $luckyNumbers = array (4,5,6,1,2,34);
        
        foreach ($luckyNumbers as $luckyNumber){
            echo "$luckyNumber <br>";
        }                 
?>
Nikita TSB
  • 440
  • 4
  • 11