Michael Fawole
Michael Fawole

Follow

Michael Fawole

Follow
For and foreach loop in php

Photo by Esther Jiao on Unsplash

For and foreach loop in php

Michael Fawole's photo
Michael Fawole
·Oct 2, 2022·

2 min read

Play this article

Table of contents

  • For Loop
  • For each Loop

Hello readers, in this article, I will be explaining for and foreach loop in php.

Let first attend to for loop.

For Loop

A for loop is used to repeat code over a particular number of times.

Below is how to iterate using for loop in php.

<?php 

for($i=0; $i<10; $i++){
echo $i;

}


?>

Let me explain the above code, ah ah ah, it is very simple and you don't need to be scared.

to use for loop, you will need to declare something like this.

<?php 

for(){

}
?>

That is the first thing for you to do. The second thing is to state the argument that will be inside the parenthesis.

$i=0; $i<10; $i++

We set variable i to be zero, it is less than 10 and we put it on incrementing.

<?php 

for($i=0; $i<10; $i++){

}
?>

The last thing under for loop is to echo whatever you want to iterate.

<?php 

for($i=0; $i<10; $i++){
echo $i;
}
?>

If you run the above code, you will get this result.

0123456789

For each Loop

I will be explaining this using an array and save it in variable called name;

$name = array();

Let input names into the array.

$name = array("Michael","Damilare","Fawole");

Now, let loop through the names using foreach loop.

foreach($name as $n){

echo $n;

}

Output: MichaelDamilareFawole

You can also add spaces in between the names by using

&nbsp;
foreach($name as $n){

echo $n.'&nbsp';

}

output > Michael Damilare Fawole

We can also add break tag to it like this.

foreach($name as $n){

echo $n.'<br>';

}

output > Michael Damilare Fawole

C__xampp_htdocs_hashnode_register_check.php • - Sublime Text (UNREGISTERED) 02-Oct-22 11_11_19 AM.png

 
Share this