Tutorials

PHP for beginners -Lesson 5

Sending
User Rating 5 (1 vote)

LoopingFOR LOOP IN PHP

Code will execute continue till condition reached false.
Syntax: for (initialization; condition; increment/decrement) { code here… }

Parameters :
initialization – set your counter, execute only once.
condition – Loop will continue till condition is TRUE.
increment/decrement – increase or decrease your counter , this parameter will execute at end of loop.

Example 1 : Display 1 to 5 numbers using For loop. <?php $i=1; for( $i = 1; $i <= 5; $i++ ){ echo $i."\t"; // \t use for TAB } ?>

Output : 1 2 3 4 5

Example 2 : Display table of input number <?php $no=5; for( $i = 1; $i <= 10; $i++ ){ echo $no*$i."\t"; } ?>

Output: 5 10 15 20 25 30 35 40 45 50

Example 3 : Fibonacci series
What is Fibonacci Numbers?
Below sequence called Fibonaci series
0,1,1,2,3,5,8,13,21,34,55,89,,144………. (f3 =f2+f1 and given f1=0, f2=1)

By definition, the first Fibonacci number is 0 and second Fibonacci number is 1. Then each subsequent number is calculated based on sum of the previous two. <?php $f1 = 0; $f2 = 1; $range = 10; for ( $i = 2; $i < $range; $i++ ){ $fn = $f1 + $f2; echo $fn."\t"; $f1 = $f2; $f2 = $fn; } ?>

Output : 1 2 3 5 8 13 21 34

Example 4 : Prime number from 1 to 100
A Prime Number can be divided – only by 1 or itself. And it must be a whole number greater than 1

<?php for( $i = 1; $i <= 100; $i++ ){ for( $j = 2; $j <= $i-1; $j++ ){ if( $i % $j == 0) break; } if($j==$i) echo $j."\t"; } ?>

Output : 2 3 5 7 11 13 17 19 23 29 31 37 41 43 47 53 59 61 67 71 73 79 83 89 97

 

Share your Thoughts