I am trying to write out all the array values using a while
loop but it isn't working, any tips?
$console = array("Wii","Playstation 3","Xbox","Dator");
echo "I like " .$console[0] . " and " . $console[1] . ".";
while($console <5){
echo "The console you like is: $console <br>";
$x++;
}
My first echo
is visible but the second one in my loop is not, what have I done wrong? The while
loop should be able to show all 4 consoles variables but it doesn't show anything.
You can get your desired output by using foreach()
and no need to use any extra function like count()
Example:
$console = array("Wii","Playstation 3","Xbox","Dator");
foreach ($console as $key => $value) {
echo $value."<br/>";
}
Result:
Wii
Playstation 3
Xbox
Dator
Also note that, while($console <5){
this condition will make your loop to infinite, if you still want to use while()
loop than you can check other answer or you can follow this example also.
<?php
$console = array("Wii","Playstation 3","Xbox","Dator");
while (list ($key, $val) = each ($console) )
echo $val."<br/>";
?>
Result:
Wii
Playstation 3
Xbox
Dator
You can also explore the manual: http://php.net/manual/en/control-structures.while.php
For the loop to be dynamic, you need to count()
the amount of items in the array and the use a counter variable ($x
in this instance) to output each iteration of the array.
<?php
$console = array("Wii","Playstation 3","Xbox","Dator");
echo "I like " .$console[0] . " and " . $console[1] . ".";
$x=0;
while($x < count($console)){
echo "The console you like is: ". $console[$x] ."<br>";
$x++;
}
?>
Read more at:
As you need to write / show all the values from the array using the while loop, you need the total number of count values and a counter. The counter track the array pointer and inside the while loop you need to increment it.
$console = array("Wii","Playstation 3","Xbox","Dator");
//echo "I like " .$console[0] . " and " . $console[1] . ".";
$count = count($console);
$counter = 0
while($counter <= $count){
echo "The console you like is: ". $console[$counter]." <br>";
$counter++;
}
You can use the foreach(){}
while will perform better for this type of array.