Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

PHP Lesson 6 Array(Warning: Undefined array key)

recently I started to teach myself php with the book Php & mysql by (Jochen Franke & Axel Borntrager).

Now I’m at lesson 6 Working with arrays: but after taking over the script I get the following Error:

Warning: Undefined array key 6 in C:\xampp\htdocs\Les – 6 Array 2.php on line 15.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

It gives the values correctly. but always followed by the error Warning: Undefined array key. What strikes me is that this is always at the beginning of the while code.
I just don’t understand where I’m making the mistake. can someone explain to me where i am making the mistake.

<html>
<head>
<title>Lesson 6 Array</title>
</head>
<body>
<?php
//Create two simple indicated arrays 
$assortment=array("table","closet","bed","nightstand ","stool","chair");
$number =array(1,5,884,34,6,12,77,93,21);

//Show all items in the array sequentially 
echo "<b>Array unsorted </b><br>";
echo "<b>assortment :</b>";
$i=0;
while($assortment[$i]){
    echo $assortment[$i] . " ";
    $i++;
}
echo "<br><b>Number:</b>";
$i=0;
while($number[$i]){
    echo $number[$i] . " ";
    $i++;
}
echo "<br><br>";
?>
</body>
</html>

>Solution :

The problem is here:

while($assortment[$i])

When $i gets to 6, you want that condition to be false; it is, but in order to discover that, PHP tries to look at the value of $assortment[6], and complains that there’s no such element in the array.

To avoid this, you could use the special isset pseudofunction:

while(isset($assortment[$i]))

(This will also end on null elements, so if you wanted to include those in a loop you’d need array_key_exists instead.)

However, a more elegant way to write the loop exists in PHP: the foreach loop:

foreach($assortment as $item) {
    echo $item . " ";
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading