PHP For loop with Example

For loop in PHP : The for loop is the most potent loop, it combines the abilities to set up variables as we enter the loop, test for conditions while iterating loops, and it modifies variables after each iteration. Example:
<?php
for ($count = 1 ; $count <= 10 ; ++$count)
echo "$count times 10 is " . $count * 10 . "<br/>";
?>

Output:
1 times 10 is 10
2 times 10 is 20
3 times 10 is 30
4 times 10 is 40
5 times 10 is 50
6 times 10 is 60
7 times 10 is 70
8 times 10 is 80
9 times 10 is 90
10 times 10 is 100
In the above example, we are outputting the 10 times table from a for loop. Each for statement takes three parameters:
  • An initialization expression.
  • A condition expression.
  • A modification expression.
These three parameters are separated by semicolons, for (exp1;exp2; exp3).
  1. The start of the first iteration of the loop, the initialization expression is executed.
  2. Each time around the loop, the condition expression is tested, and the loop is entered only if the condition is TRUE.
  3. At the end of each iteration,the modification expression is executed.
Example (Even Numbers from 1 to 100):
<?php
for ($i=2; $i<=100; $i+=2)
{
 echo $i." ";
}
?>

Output:
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 46 48 50 52 54 56 58 60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100

  • In the above example, for loop from ($i=2) and after every count, $i increment its value by 2, which print all the even value from 1 to 100.
Example (Pattern1):
<?php
for ($i=1; $i<=5; $i++)         
{          
for($j=1;$j<=$i;$j++)           
{                      
echo $j." ";     
}                      
echo "<br/>";           
} 
?>
Output:
1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
Example (Pattern2):
<?php
for ($i=1; $i<=10; $i++)       
{          
for($j=1;$j<=$i;$j++)           
{                      
echo $i." ";     
}                      
echo "<br/>";           
} 
?>
Output:
1 
2 2 
3 3 3 
4 4 4 4 
5 5 5 5 5 
6 6 6 6 6 6 
7 7 7 7 7 7 7 
8 8 8 8 8 8 8 8 
9 9 9 9 9 9 9 9 9 
10 10 10 10 10 10 10 10 10 10 
Example (Pattern3):
<?php
for ($i=1; $i<=5; $i++)         
{          
for($j=1;$j<=$i;$j++)           
{                      
echo " * ";      
}                      
echo "<br/>";           
} 
?>
Output:
* 
* * 
* * * 
* * * * 
* * * * *
Example (Pattern4):
<php
for ($i=1; $i<=10; $i++)       
{          
for ($k=10; $k>$i; $k--)       
{          
//print one space through html ;
echo " ";         
}          
for($j=1;$j<=$i;$j++)           
{                      
echo "*";        
}                      
echo "<br/>";           
}
?>
Output:
         *
        **
       ***
      ****
     *****
    ******
   *******
  ********
 *********
**********
Example (Pattern5):
<?php 
for($i=0;$i<=10;$i++)
{ 
for($j=10-$i;$j>=1;$j--)
{ 
echo "* "; 
} 
echo "<br>"; 
} 
?>
Output:
* * * * * * * * * * 
* * * * * * * * * 
* * * * * * * * 
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
*
Example (Pattern6):
<?php
for($i=0;$i<=10;$i++)
{ 
for($k=10;$k>=$i;$k--)
{ 
echo "  "; 
} 
for($j=1;$j<=$i;$j++)
{ 
echo "*  "; 
} 
echo "<br>"; 
} 
for($i=9;$i>=1;$i--)
{ 
for($k=10;$k>=$i;$k--)
{ 
echo "   "; 
} 
for($j=1;$j<=$i;$j++)
{ 
echo "*  "; 
} 
echo "<br>"; 
} 
?>
Output:
                   *  
                 *  *  
               *  *  *  
             *  *  *  *  
           *  *  *  *  *  
         *  *  *  *  *  *  
       *  *  *  *  *  *  *  
     *  *  *  *  *  *  *  *  
   *  *  *  *  *  *  *  *  *  
 *  *  *  *  *  *  *  *  *  *  
   *  *  *  *  *  *  *  *  *  
     *  *  *  *  *  *  *  *  
       *  *  *  *  *  *  *  
         *  *  *  *  *  *  
           *  *  *  *  *  
             *  *  *  *  
               *  *  *  
                 *  *  
                   *  

Example (Pattern7)
<?php
for($i=1; $i<=10; $i++)
{  
for($j=1; $j<=$i; $j++)
{  
echo ' * ';  
} 
echo '<br>';  
} 
for($i=10; $i>=1; $i--)
{  
for($j=1; $j<=$i; $j++)
{ 
echo ' * ';  
}  
echo '<br>';  
}  
?>
Output:
* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * * * 
* * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * 
* * * * * * * * 
* * * * * * * 
* * * * * * 
* * * * * 
* * * * 
* * * 
* * 
* 
Example (Table using for loop):
<html>
<body>
<form method="post">
<table align="center">
<tr>
<td>
Enter Number of Rows
</td>
<td>
<input type="text" name="r"/>
</td>
</tr>
<br>
<tr>
<td>
Enter Number of Cols </td>
<td>
<input type="text" name="c"/>
</td>
</tr>
<br>
<tr>
<td colspan="2" align="center">
<input type="submit" value="Create Table" name="create"/>
</td>
</tr>
</form>
</table>
</body>
</html>
<?php
if(isset($_POST['create']))
{
$rows=$_POST['r'];
$cols=$_POST['c'];
echo "<table border='1' align='center'>";
for($i=0;$i<$rows;$i++)
{
echo "<tr>";
for($j=0;$j<$cols;$j++)
{
echo "<th>"."r".$i."c".$j."</th>";
}
echo "</tr>";
}
echo "</table>";
}
?>
Output: PHP for Loop Example

Related Topics

PHP array_map() Function

PHP array_map() Function The array_map() function  in PHP is used to return an array containing the results of applying the user-defined callback function over the elements of one or more arrays. Syntax array_map ( callable $callback , array $array1 [, array $... ] )  Parameter callable(required)- This parameter...

1 minute read.

PHP Comment

PHP commentis a line of code that is not executed. It is often used by developer to understand the code. PHP support single and multiple comments. In other language like C,...

1 minute read.

PHP is_long() Function

The PHP is_long () function in PHP is used to find whether a variable is an integer or not. It returns a Boolean value true if the parameter var is integer else it returns...

1 minute read.

PHP setlocale() Function

PHP setlocale() Function The setlocale() function in PHP sets locale information(language, monetary, time and, other information specific for a geographical area.) Syntax setlocale ( int $category , array $locale ) Parameter category(required)- This parameter specified a named constant specifying the category of the functions affected...

1 minute read.

PHP str_replace() Function

PHP str_replace() Function The str_replace() function in PHP replaces all occurrences of the search string with the specified replacement string. This function is case-sensitive. Syntax str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] ) Parameter search(required)- This parameter signifies the value to search. replace(required)-...

1 minute read.

PHP end() function

PHP end() function The end() function in PHP sets the internal pointer of an array to its last element. This function returns the value of the last element Syntax end ( array &$array )   Parameter array (required)– This parameter represents the input array. Return This function returns...

1 minute read.

PHP strnatcmp() Function

PHP strnatcmp() Function The strnatcmp() function in PHP compares two strings using a "natural" algorithm. It is case-sensitive. Syntax strnatcmp ( string $str1 , string $str2 ) Parameter str1(required)- This parameter represents the first string. str2(required)- This parameter represents the second string. Return This function returns a value less than(...

1 minute read.

PHP array_intersect_uassoc() function

The array_intersect_uassoc () function in PHP is used to compute the intersection of arrays with the help of an additional index check, comparing indexes by a callable function. It returns an array containing...

1 minute read.

PHP array_multisort() Function

PHP array_multisort () Function The array_multisort() function in PHP sorts multiple or multi-dimensional arrays at once. Syntax array_multisort ( array &$array1 [, mixed $array1_sort_order [, mixed $array1_sort_flags [, mixed $... ]]] ) Parameter array1(required)- This parameter specified the input array to sort. array1_sort_order(optional)- This parameter specifies the order (ascending or descending)...

1 minute read.

PHP array_diff_uassoc() Function

PHP array_diff_uassoc() Function The array_diff_uassoc () Function in PHP is used to compare the keys and values of two (or more) arrays and returns the differences (an array containing the entries from the first array that...

1 minute read.

PHP quoted_printable_decode() Function

PHP quoted_printable_decode() Function The quote_printable_decode() function of PHP converts a quoted-printable string to an 8 bit string. It works similar to imap_qprint(), except this one does not require the IMAP module to work. Syntax quoted_printable_decode ( string $str ) Parameter str(required)- This parameter represents the...

1 minute read.

PHP While Loop

PHP while loop is used to run the same block of code until a condition is met. It should be used if number of iteration it not known. Syntax: <?php while (condition){   //Code...

1 minute read.

PHP echo() Function

PHP echo() Function The echo() function in PHP outputs or displays one or more strings. The major differences between print() function and echo() function is that echo accepts an argument list and doesn't have a return value. Also, it is slightly...

1 minute read.

PHP rtrim() Function

PHP rtrim() Function The rtrim() function in PHP is used to strip off the whitespace (or other characters) from the end of a string. If the second parameter is not specified, this function will strip are...

1 minute read.

PHP natcasesort() Function

PHP natcasesort() Function The natcasesort() function in PHP Sort an array using a case insensitive "natural order" algorithm while maintaining the keys. Syntax natcasesort ( array &$array ) Parameter array(required)- This parameter represents the input array. Return This parameter returns a Boolean...

1 minute read.

PHP nl2br() Function

PHP nl2br() Function The nl2br() function in PHP inserts HTML line breaks before all newlines in a string. Syntax nl2br ( string $string [, bool $is_xhtml] ) Parameter sting(required)- This parameter specifies the input string. is_xhtml(optional)- This parameter states whether to use XHTML compatible line breaks...

1 minute read.

PHP array_unique() Function

PHP array_unique() Function The array_unique() function in PHP removes the duplicate values from the specified array. Syntax array_unique (array $array [, int $sort_flags = SORT_STRING]) Parameter array(required)- This array represents the first input array. sort_flags (optional)- This parameter is used to modify the sorting behavior. The...

1 minute read.

PHP money_format() Function

PHP money_format() Function The money_format() function in PHP formats a number as a currency string and returns a formatted version of number. Syntax money_format ( string $format , float $number )  Parameter format(required)- This parameter specifies the string to be formatted and how to format the...

1 minute read.

Python main() function

What is a main() function? In most of the programming languages, there is this one special function i.e., main() which is executed firstly everytime when we run the program. The special...

6 minutes read.

WordPress Plugin

WordPress Plugin is a process used to add or extend the functionality which can be enabled or disabled, and it does not interfere with the software and its code. WordPress is lightweight and smooth...

2 minutes read.