For and foreach loop in PHP with break statement and creating patterns using nested for loops
We can print numbers from 1 to 10 by using for loop. You can easily extend this program to print any numbers from starting from any value and ending on any value.
The echo command will print the value of $i to the screen. In the next line we have used the same echo command to print one html line break. This way all numbers will be printed in one new line.
More Details on FOR loop
Here we have printed from 1 to 10 numbers, by changing the values inside the for loop you can print numbers starting from any value to ending at any value.
What happens when we keep a condition which the loop can never meets?
for( $i=1; $i<=10; $i++ )
{
echo $i;
$i = 5;
}
Inside the loop each time we are resetting the value of $i to 5 , so it can never reach value of 10 to exit the loop.
Output is here.
....
Fatal error: Maximum execution time of 30 seconds exceeded in H:\php_files\plus2net\z\for.php on line 18
Server stops the execution of the script after 30 seconds. This value of 30 seconds is set at php.ini file, we can change this upper limit of execution time by using ini_set() function.
Just add this line to the above code.
error_reporting(E_ALL); // Display all types of error
set_time_limit ( 2 ); // Max execution time is set to 2 seconds
for( $i=1; $i<=10; $i++ )
{
echo $i;
$i = 5;
}