Jump to content
j.silver

Vague Notice

Recommended Posts

Hi,

This block code is from W3schools tutorials:

<?php
$cars = array("Volvo", "BMW", "Toyota");
$arrlength = count($cars);
for($x = 0; $x <= $arrlength; $x++) {
echo $cars[$x];
echo "<br>";
}
?>
The original block was without the equal sign in $x <= $arrlength;
I have added the equal sign to see what would happen. I got the same result but followed with:
Notice: Undefined offset: 3 in C:\xampp\htdocs\Testing\testing.php on line 14
I would appreciate it if someone would explain why I am getting this notice and its meaning. I thought the loop will stop and give the same result without any notice when it hits no value for the equal sign.

Share this post


Link to post
Share on other sites

The length of the array is 3, and you are telling it to loop as long as $x is less than or equal to 3. When $x is 3 it tries to access $cars[3], which does not exist.

Share this post


Link to post
Share on other sites

An array index value always begin with 0, so index will be 0, 1, 2, the array length will produce 3, using equals will index value 3 as the loop finishes, which as you can see does not exist.

Share this post


Link to post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...