PHP Loops
We will talk about 3 specific PHP Loops: The While Loop, The For Loop, and The Foreach Loop.
Let's write our code in an HTML file and write our first While Loop
.
<!DOCTYPE html>
<html>
<head>
<title>My First PHP App</titile>
</head>
<body>
<?php $number = 0 ?>
</body>
</html>
you need to enclose your code with the PHP start tag
<?php
and the PHP end tag?>
when integrating PHP code with HTML content.
We added a variable with the value of 0
. We then want to add an unordered list and loop through a certain number of list items.
<!DOCTYPE html>
<html>
<head>
<title>My First PHP App</titile>
</head>
<body>
<?php $number = 0 ?>
<ul>
<?php while( $number <10 ) {
echo '<li>' . $number . '</li>';
$number++;
}
?>
</ul>
</body>
</html>
We are telling the code that
while( $number < 10)
, we want to print out a list item with the current number :
echo '<li>' . $number . '</li>';
and finnally we are encrementing the $number
by 1: $number++;
.
Also, it's important to mention that there is another version of the while
loop, which is called the Do While Loop. We just put the do
statement in the beginning and the while
statement with the condition at the end.
<!DOCTYPE html>
<html>
<head>
<title>My First PHP App</titile>
</head>
<body>
<?php $number = 0 ?>
<ul>
<?php do {
echo '<li>' . $number . '</li>';
$number++;
} while( $number <10 )
?>
</ul>
</body>
</html>