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 trim() Function

PHP trim() Function The trim() Function in PHP strips the whitespace or other characters from the beginning and the end of the given string. The trim() function strips the following characters: " " - an ordinary space."\t"- a tab."\n"- a new...

1 minute read.

PHP arsort() function

PHP arsort() function The arsort() function in PHP sorts an array in the reverse order and maintains the index association Syntax arsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) Parameter array(required)- This parameter represents the input array. sort_flags (optional)- This parameter is used to modify the behavior...

2 minutes read.

PHP asort() function

PHP asort() function The asort() function in PHP is used to sort an array while maintaining the index association. Syntax asort ( array &$array [, int $sort_flags = SORT_REGULAR ] )  array(required)- This parameter represents the input array to sort. sort_flags (optional)- This parameter is used to...

1 minute read.

PHP strstr() Function

PHP strstr() Function The strstr() function in PHP finds the first occurrence of a string. It returns part of the parameter haystack string starting from and including the first occurrence of needle to the end of the haystack parameter. This function is case-sensitive.  Syntax strstr ( string $haystack , mixed $needle [, bool $before_needle] )  Parameter  haystack(required)-...

2 minutes 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 Echo And Print

In PHP, echo and print is used to get output data to the screen but there is some difference, between echo and print. PHP echo PHP echo is used to display the...

1 minute read.

PHP sha1() Function

PHP sha1() Function The sha1() in PHP calculates the SHA-1 hash of a string. Syntax sha1 ( string $str [, bool $raw_output = FALSE ] )  Parameter str (required)- This parameter represents the input string. raw_output(optional)- This parameter takes Boolean value and returns the digest in raw binary format...

1 minute read.

PHP join() Function

PHP join() Function The join() function of PHP returns a string from the elements of an array. This function is an alias of the implode() function. Syntax join(separator,array) Parameter separator(Optional)- Specifies what to put between the array elements. The default...

1 minute read.

PHP array_values() Function

PHP array_values() Function The array_values () function in PHP returns all the values from the array and indexes the array numerically. Syntax array_values ( array $array ) Parameter array(required)- This array represents the input array. Return This function returns an indexed array of values. Example 1 Output Input Array: Array ...

1 minute read.

PHP rsort() Function

PHP rsort() Function The rsort () function in PHP is used to sort an array in reverse order i.e., highest to lowest. Syntax rsort ( array &$array [, int $sort_flags = SORT_REGULAR ] ) Parameter array(required)- This parameter represents the input array. sort_flags (optional)- This parameter is used to...

1 minute read.

PHP print() Function

PHP print() Function The print() function in PHP is used to output one or more string. Syntax print ( string $arg ) Parameter arg(required)- This parameter represents the input data. It can take one or more arguments. Return This function returns an integer value 1. Example...

1 minute read.

PHP htmlspecialchars_decode() Function

PHP htmlspecialchars_decode() Function The htmlspecialchars_decode() function in PHP convert some predefined HTML entities to characters. The some predefined HTML entities that will be decoded are as follows: &amp; OR & (ampersand)&quot; OR " (double quote)&#039;...

2 minutes read.

PHP quoted_printable_encode() Function

PHP quoted_printable_encode() Function The quoted_printable_encode() function in PHP converts a 8 bit string to a quoted-printable string. This function is similar to imap_8bit(), except this one does not require the IMAP module to work. Syntax quoted_printable_encode ( string $str ) Parameter str(required)- This parameter represents...

1 minute read.

PHP Validation

PHP validation is used to check whether the field is filled or not in the proper way by the user. There are two types of validation in PHP. Client Side Validation:...

5 minutes read.

PHP For Loops

PHP for loop is used when the specified condition is predefined. Syntax: for (initialization; condition; increment/decrement ) { code to be executed; } Example <!DOCTYPE html> <html> <head> <title>PHP Tutorial</title> </head> <body> <?php echo " Print counting using for loop"."<br>"; for($i=1;$i<=5;$i++){ echo $i."<br>"; } ?> </body> </html> Output Print counting using...

1 minute read.

PHP is_scalar() Function

PHP is_scalar() Function The is_scalar() function in PHP finds whether a variable is a scalar or not. It returns a Boolean value TRUE if the parameter var is scalar, else it returns FALSE. Scalar variables are those containing an integer, float, string or boolean. This...

1 minute read.

PHP sprintf() Function

PHP sprintf() Function The sprintf() function in PHP is used to write a formatted string to a variable and returns a formatted string. PHP 4 and above versions support the sprintf() function. The related functions are...

8 minutes read.

PHP array_walk_recursive() Function

PHP array_walk_recursive() Function The array_walk_recursive () function in PHP is used to apply a user-defined callback function recursively to each element of the array. This function returns a Boolean TRUE on success or FALSE on failure. Syntax array_walk_recursive ( array &$array , callable $callback [, mixed $userdata = NULL ] ) Parameter array(required)- This array represents the...

1 minute read.

PHP vsprintf() Function

PHP vsprintf() Function The vsprintf() function in PHP returns a formatted string. This function accepts an array of arguments. Syntax vsprintf ( string $format , array $args ) Parameter format(required)- This parameter specifies the string and how to format the variables in it. The conversion specification of this parameter...

3 minutes read.

PHP addslashes() Function

PHP addslashes() Function The addslashed() function in PHP is used to return a string with backslashes in front of predefined characters. This function is only used with some characters which are...

1 minute read.