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

PHP convert_cyr_string() Function The convert_cyr_string() function in PHP converts from one Cyrillic character-set to another. The supported characters set are given below: k - koi8-rw - windows-1251i - iso8859-5a - x-cp866d - x-cp866m...

1 minute read.

PHP Magic Constants

There are various predefine PHP Magic Constants. It starts with underscore(__) and ends with double underscore.  Magic Constant Description __LINE__ To check current line number of the file. __FILE__ To check full path and filename of...

1 minute read.

PHP array_udiff() Function

PHP array_udiff() Function The array_udiff() function in PHP calculates the difference of arrays by using a callback function for data comparison. Syntax array_udiff ( array $array1 , array $array2 [, array $... ], callable $value_compare_func ) Parameter array1(required)- This array represents the first input array. array2(required)- This array represents the second input array. array3….(optional)- It...

1 minute read.

PHP stripos() Function

PHP stripos() Function The stripos() function in PHP finds the position of the first occurrence of a substring in the specified string. It is a case-insensitive a binary-safe function. The related functions are as follows: strripos() Functionstrpos() Functionstrrpos() Function Syntax stripos ( string $haystack , mixed $needle [, int $offset...

1 minute read.

PHP $ and $$ Variables

PHP $var variable is a normal variable that stores any value. PHP $$var variable is a reference variable that stores the value of$var inside it. Let us take an example. Example 1 <?php $x =...

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

PHP str_shuffle() Function The str_shuffle() function in PHP randomly shuffles all the characters of the specified string. Syntax str_shuffle ( string $str ) Parameter str(required)- This parameter represents the input string to shuffle. Return This function returns the shuffled string. Example 1 ...

1 minute read.

PHP chop() Function

PHP chop() Function The chop() function in PHP removes whitespaces or other predefined characters from the right end of the specified string. Syntax chop(str,charlist) Parameter str(required)- This parameter specifies the string to check. charlist(optional)- This parameter...

1 minute read.

PHP strrchr() Function

PHP strrchr() Function The strrchr() function in PHP finds the last occurrence of a character in the specified string and returns the portion of haystack, which starts at the last occurrence of the needle and goes until the end of haystack....

1 minute read.

PHP strripos() Function

PHP strripos() Function The strripos() function in PHP finds the position of the last occurrence of a substring in the specified string. It is a case-insensitive and binary-safe function. Syntax strripos ( string $haystack , mixed $needle [, int $offset ] ) Parameter haystack(required)- This parameter signifies the...

1 minute read.

PHP array_walk() Function

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

1 minute read.

PHP next() Function

PHP next() Function The next() function in PHP advances or moves the internal array pointer one place forward and returns the next array value. Syntax next ( array &$array ) Parameter array(required)- This parameter represents the input array. Return This parameter returns the next array value...

1 minute read.

PHP foreach Loop

PHP foreach Loop with Example PHP foreach loop is used to loop through the associative arrays. Syntax: foreach($array as $key => $value) { //Statement } $array = associative array. $key = array key. &value =...

2 minutes read.

PHP array_key_last() function

The array_key_last () function in PHP gets the last key of an array if the specified array is not empty. Syntax array_key_last ( array $array )  Parameter array(required)- This parameter signifies the input array. Return This function returns the last key of the...

1 minute read.

Composer Installation

Composer is an application-level package manager for the PHP Programming language. The development began in April 2011 and it was first released on March 1, 2012. Commands: require install update remove Installation:  Download the installer by visiting...

1 minute read.

PHP array_slice() Function

PHP array_slice() Function The array_slice() function in PHP is used to extract a slice of the array. It returns the sequence of elements from the array as specified by the offset and length parameters. Syntax array_slice ( array $array , int $offset [, int $length = NULL [, bool $preserve_keys = FALSE ]] ) Parameter array(required)- This array represents the...

2 minutes read.

PHP array_intersect() function

The array_intersect () function in PHP is used to compute the intersection of arrays. It returns an array containing all the entries from array1 that are present in all the other arrays. Syntax array_intersect ( array $array1 , array $array2 [, array $... ]) Parameter array1(required)- This parameter...

1 minute read.

PHP array_intersect_assoc() function

PHP array_intersect_assoc() function The array_intersect_assoc() function in PHP is used to compute the intersection of arrays with the help of an additional index check. It returns an array containing all the entries from array1 that are present...

1 minute read.

PHP array_product() Function

PHP array_product() Function The array_product() function in PHP calculates the product of values in an array. Syntax array_product ( array $array ) Parameter array(required)- This parameter represents the input array. Return This function returns the product of the array elements as an integer or float....

1 minute read.