Thursday, June 20, 2013

php for loop - foreach php

php for loop
In this lesson we will talk about php for loop, there are fore type of loops in php
while,for,do..while and foreach we will talk about for loop in this lesson
for (init, condition, increment)
{
what we want to repeat;
}
init: the variable and it's first value
condition: if it's true the loop continue and if it false the loop stop
increment: the value to be added to the counter
Let's say that we want to print numbers from 1 to 10, we can write the code like this
<?php
echo '1';
echo '2';
.
.
.
echo '10';
?>
And if we using php for loop we will write the code like this
<?php
$i=1;
for($i=1; $i<=10; $i++)
{
echo "$i"." ";
}
?>
We will see 1 2 3 4 5 6 7 8 9 10 on the screen
we use this ." " to put distances between numbers
This was the php for loop, now let's move to the foreach php loop
foreach ($array as $value)
{
what we want to do;
}
foreach php loop using with arrays
Let's define four values in one array and try to print theme on the screen, the code will be like this
<?php
$numbers = array('one','four','nine','twelve');
foreach($numbers as $value)
{
echo "$value"." ";
}
?>
We will see this on the screen
foreach php


This was the foreach php loop i hope you enjoy the lesson
we will talk about while and do..while, when we get to database lesson, if you have any question just leave a comment.
see you next time.




Share This!



No comments :

Post a Comment