For and foreach loop in php
Table of contents
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
foreach($name as $n){
echo $n.' ';
}
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
Subscribe to my newsletter
Read articles from Michael Fawole directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Michael Fawole
Michael Fawole
Michael Fawole is a Blockchain and web application developer with 7+ years of experience and 3+ years plus of experience in blockchain dapp development. He is also delivering training on blockchain ( Solidity, web3 and react js ) and php language. He also helps start-ups and companies to setup blockchain practice and incorporating blockchain into existing project. Techstack (Blockchain): Solidity, web3 js and react js. Techstack (Webapp): Php and Mysql.