Owl City
Owl City

Reputation: 35

PHP: while loop is infinite

<?php 
$animals = array('pig', 'chicken', 'cow', 'snake');
$i = 0;
while ($i < 10)
{
    echo "<li>$animals[$i]</li>";
}
?>

I just wanna see the pig, chicken, cow and snake in list item.. but what happen is it just looping the word pig infinitely...

Upvotes: 1

Views: 3737

Answers (7)

You haven't incremented the $i value so it is always $i = 0; so it always under 10.

Add $i++ to increment it to avoid this, but with this code you get another new problem, because the array is having only 3 elements and you are using 10 in the while loop.

<?php 
    $animals = array('pig', 'chicken', 'cow', 'snake');
    $i = 0;
    while ($i < 10)
    {
        echo "<li>$animals[$i]</li>";
        $i++;
    }
?>

Upvotes: 0

Praveen reddy Dandu
Praveen reddy Dandu

Reputation: 198

<?php 
  $animals = array('pig', 'chicken', 'cow', 'snake');
  $i = 0;
  $max = sizeof($animals);
  while ($i < max) {
    echo "<li>$animals[$i]</li>";
    i++;
  }
?>

Upvotes: 0

Ankur Tiwari
Ankur Tiwari

Reputation: 2782

I have added $i++; which is increment the value of $i by one each time in the loop, so we are able to display each element of array also find length of array in initial to avoid array out-of-bound problem.

<?php 
 $animals = array('pig', 'chicken', 'cow', 'snake');
 $i = 0;
 $len = count($animals);
    while ($i < $len) 
    {
       echo "<li>$animals[$i]</li>";
       $i++;
    }

 ?>

Initially count the length of array and then iterate the loop according to length.

Upvotes: 1

Wee Zel
Wee Zel

Reputation: 1324

i do like a while loop, so here's one more for the mix! :)

<?php
$animals = array('pig', 'chicken', 'cow', 'snake');
while ($animal = next($animals)) {
    echo "<li>$animal[$i]</li>";
}
?>

this uses next() to get each value of the array, this returns false when its gets to the end of the array terminating the while loop. You don't need to control getting elements of the array using $i and you don't need extra if statements inside the loop checking if your element exists

Upvotes: 0

gommb
gommb

Reputation: 1119

this should loop through the array by using $i++ which increments the $i variable by one.

<?php 
 $animals = array('pig', 'chicken', 'cow', 'snake');
 $i = 0;
while ($i < 4) {
    echo "<li>$animals[$i]</li>";
    $i++;
 }
 ?>

Upvotes: 2

Hassaan
Hassaan

Reputation: 7662

You are not adding increment to $i. You can add increment to $i by adding $i++ in your while loop.

<?php 
$animals = array('pig', 'chicken', 'cow', 'snake');
$i = 0;
while ($i < 10)
{
    if (isset($animals[$i]))
    {
        echo "<li>$animals[$i]</li>";
    }
    $i++
}
?>

Upvotes: 2

Sunny
Sunny

Reputation: 119

You can also use foreach to do this

$animals = array('pig', 'chicken', 'cow', 'snake');
foreach($animals as $animal)
echo "<li>{$animal}</li>";

Upvotes: 1

Related Questions