PHP if else statement is used to test condition. There are various ways to use if statement in PHP.
PHP if statement allows conditional execution of code. It is executed if condition is true.If statement is used to executes the block of code exist inside the if statement only if the specified condition is true.
$num =12; if($num <100){ echo "$num is less than 100"; } op:12 is less than 100If-else Statement
PHP if-else statement is executed whether condition is true or false.If-else statement is slightly different from if statement. It executes one block of code if the specified condition is true and another block of code if the condition is false.
$num=12; if($num%2==0){ echo "$num is even number"; }else{ echo "$num is odd number"; } op:12 is even numberIf-else-if Statement
The PHP if-else-if is a special statement used to combine multiple if?.else statements. So, we can check multiple conditions using this statement.
$marks=69; if ($marks<33){ echo "fail"; } else if ($marks>=34 && $marks<50) { echo "D grade"; } else if ($marks>=50 && $marks<65) { echo "C grade"; } else if ($marks>=65 && $marks<80) { echo "B grade"; } else if ($marks>=80 && $marks<90) { echo "A grade"; } else if ($marks>=90 && $marks<100) { echo "A+ grade"; } else { echo "Invalid input"; } op:B Gradenested if Statement
The nested if statement contains the if block inside another if block. The inner if statement executes only when specified condition in outer if statement is true.
$age = 23; $nationality = "Indian"; //applying conditions on nationality and age if ($nationality == "Indian") { if ($age >= 18) { echo "Eligible to give vote"; } else { echo "Not eligible to give vote"; } } op:Eligible to give vote
PHP switch statement is used to execute one statement from multiple conditions. It works like PHP if-else-if statement.
Syntaxswitch(expression){ case value1: //code to be executed break; case value2: //code to be executed break; ...... default: code to be executed if all cases are not matched; }Important points to be noticed about switch case:
$num=20; switch($num){ case 10: echo("number is equals to 10"); break; case 20: echo("number is equal to 20"); break; case 30: echo("number is equal to 30"); break; default: echo("number is not equal to 10, 20 or 30"); } op:number is equal to 20PHP switch statement is fall-through
PHP switch statement is fall-through. It means it will execute all statements after getting the first match, if break statement is not found.
$ch = 'c'; switch ($ch) { case 'a': echo "Choice a"; break; case 'b': echo "Choice b"; break; case 'c': echo "Choice c"; echo ""; case 'd': echo "Choice d"; echo ""; default: echo "case a, b, c, and d is not found"; } op: Choice c Choice d case a, b, c, and d is not foundnested switch statement
Nested switch statement means switch statement inside another switch statement. Sometimes it leads to confusion.
$car = "Hyundai"; $model = "Tucson"; switch( $car ) { case "Honda": switch( $model ) { case "Amaze": echo "Honda Amaze price is 5.93 - 9.79 Lakh."; break; case "City": echo "Honda City price is 9.91 - 14.31 Lakh."; break; } break; case "Renault": switch( $model ) { case "Duster": echo "Renault Duster price is 9.15 - 14.83 L."; break; case "Kwid": echo "Renault Kwid price is 3.15 - 5.44 L."; break; } break; case "Hyundai": switch( $model ) { case "Creta": echo "Hyundai Creta price is 11.42 - 18.73 L."; break; case "Tucson": echo "Hyundai Tucson price is 22.39 - 32.07 L."; break; case "Xcent": echo "Hyundai Xcent price is 6.5 - 10.05 L."; break; } break; } op:Hyundai Tucson price is 22.39 - 32.07 L.
PHP for loop can be used to traverse set of code for the specified number of times.
It should be used if the number of iterations is known otherwise use while loop. This means for loop is used when you already know how many times you want to execute a block of code.
Syntaxfor(initialization; condition; increment/decrement){ //code to be executed }
for($n=1;$n<=10;$n++){ echo "$n
"; } op:
All three parameters are optional, but semicolon (;) is must to pass in for loop. If we don't pass parameters, it will execute infinite.
$i = 1; //infinite loop for (;;) { echo $i++; echo ""; }
Below is the example of printing numbers from 1 to 9 in four different ways using for loop.
/* example 1 */ for ($i = 1; $i <= 9; $i++) { echo $i; } echo ""; /* example 2 */ for ($i = 1; ; $i++) { if ($i > 9) { break; } echo $i; } echo ""; /* example 3 */ $i = 1; for (; ; ) { if ($i > 9) { break; } echo $i; $i++; } echo ""; /* example 4 */ for ($i = 1, $j = 0; $i <= 9; $j += $i, print $i, $i++); op: 123456789 123456789 123456789 123456789Nested For Loop
for($i=1;$i<=3;$i++){ for($j=1;$j<=3;$j++){ echo "$i $j
"; } } op: 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3
The foreach loop is used to traverse the array elements. It works only on array and object. It will issue an error if you try to use it with the variables of different datatype.
The foreach loop works on elements basis rather than index. It provides an easiest way to iterate the elements of an array.
Syntaxforeach ($array as $value) { //code to be executed } There is one more syntax of foreach loop. foreach ($array as $key => $element) { //code to be executed }
PHP program to print array elements using foreach loop. $season = array ("Summer", "Winter", "Autumn", "Rainy"); //access array elements using foreach loop foreach ($season as $element) { echo "$element"; echo ""; } op: Summer Winter Autumn Rainy PHP program to print associative array elements using foreach loop. //declare array $employee = array ( "Name" => "Alex", "Email" => "alex_jtp@gmail.com", "Age" => 21, "Gender" => "Male" ); //display associative array element through foreach loop foreach ($employee as $key => $element) { echo $key . " : " . $element; echo ""; } op: Name : Alex Email : alex_jtp@gmail.com Age : 21 Gender : Male Multi-dimensional array //declare multi-dimensional array $a = array(); $a[0][0] = "Alex"; $a[0][1] = "Bob"; $a[1][0] = "Camila"; $a[1][1] = "Denial"; //display multi-dimensional array elements through foreach loop foreach ($a as $e1) { foreach ($e1 as $e2) { echo "$e2\n"; } } op:Alex Bob Camila Denial Dynamic array //dynamic array foreach (array ('j', 'a', 'v', 'a', 't', 'p', 'o', 'i', 'n', 't') as $elements) { echo "$elements\n"; } op:j a v a t p o i n t
PHP while loop can be used to traverse set of code like for loop. The while loop executes a block of code repeatedly until the condition is FALSE. Once the condition gets FALSE, it exits from the body of loop.
It should be used if the number of iterations is not known.
The while loop is also called an Entry control loop because the condition is checked before entering the loop body. This means that first the condition is checked. If the condition is true, the block of code will be executed.
Syntaxwhile(condition){ //code to be executed } //Alternative Syntax while(condition): //code to be executed endwhile;
$n=1; while($n<=10){ echo "$nNested While Loop
"; $n++; } op: Alternative Example $n=1; while($n<=10): echo "$n
"; $n++; endwhile; op: //Below is the example of printing alphabets using while loop. $i = 'A'; while ($i < 'H') { echo $i; $i++; echo ""; } op: A B C D E F G
We can use while loop inside another while loop in PHP, it is known as nested while loop.
In case of inner or nested while loop, nested while loop is executed fully for one outer while loop. If outer while loop is to be executed for 3 times and nested while loop for 3 times, nested while loop will be executed 9 times (3 times for 1st outer loop, 3 times for 2nd outer loop and 3 times for 3rd outer loop).
$i=1; while($i<=3){ $j=1; while($j<=3){ echo "$i $jInfinite While Loop
"; $j++; } $i++; } op: 1 1 1 2 1 3 2 1 2 2 2 3 3 1 3 2 3 3
If we pass TRUE in while loop, it will be an infinite loop.
Syntaxwhile(true) { //code to be executed }
while (true) { echo "Hello Javatpoint!"; echo ""; }
PHP do-while loop can be used to traverse set of code like php while loop. The PHP do-while loop is guaranteed to run at least once.
The PHP do-while loop is used to execute a set of code of the program several times. If you have to execute the loop at least once and the number of iterations is not even fixed, it is recommended to use the do-while loop.It executes the code at least one time always because the condition is checked after executing the code. The do-while loop is very much similar to the while loop except the condition check. The main difference between both loops is that while loop checks the condition at the beginning, whereas do-while loop checks the condition at the end of the loop.
Syntaxdo{ //code to be executed }while(condition);
$n=1; do{ echo "$n
"; $n++; }while($n<=10);
A semicolon is used to terminate the do-while loop. If you don't use a semicolon after the do-while loop, it is must that the program should not contain any other statements after the do-while loop. In this case, it will not generate any error.
$x = 5; do { echo "Welcome to javatpoint! "; $x++; } while ($x < 10); op: Welcome to javatpoint! Welcome to javatpoint! Welcome to javatpoint! Welcome to javatpoint! Welcome to javatpoint!
The following example will increment the value of $x at least once. Because the given condition is false.
$x = 1; do { echo "1 is not greater than 10."; echo ""; $x++; } while ($x > 10); echo $x; op: 1 is not greater than 10. 2Difference between while and do-while loop
while Loop | do-while loop |
---|---|
The while loop is also named as entry control loop. | The do-while loop is also named as exit control loop. |
The body of the loop does not execute if the condition is false. | The body of the loop executes at least once, even if the condition is false. |
Condition checks first, and then block of statements executes. | Block of statements executes first and then condition checks. |
This loop does not use a semicolon to terminate the loop. | Do-while loop use semicolon to terminate the loop. |
PHP break statement breaks the execution of the current for, while, do-while, switch, and for-each loop. If you use break inside inner loop, it breaks the execution of inner loop only.
The break keyword immediately ends the execution of the loop or switch structure. It breaks the current flow of the program at the specified condition and program control resumes at the next statements outside the loop.
The break statement can be used in all types of loops such as while, do-while, for, foreach loop, and also with switch case.
Syntaxjump statement; break;Break: inside loop
for($i=1;$i<=10;$i++){ echo "$iBreak: inside inner loop
"; if($i==5){ break; } } op: 1 2 3 4 5
for($i=1;$i<=3;$i++){ for($j=1;$j<=3;$j++){ echo "$i $jBreak: inside switch statement
"; if($i==2 && $j==2){ break; } } } op: 1 1 1 2 1 3 2 1 2 2 3 1 3 2 3 3
$num=200; switch($num){ case 100: echo("number is equals to 100"); break; case 200: echo("number is equal to 200"); break; case 50: echo("number is equal to 300"); break; default: echo("number is not equal to 100, 200 or 500"); } op: number is equal to 200Break: with array of string
//declare an array of string $number = array ("One", "Two", "Three", "Stop", "Four"); foreach ($number as $element) { if ($element == "Stop") { break; } echo "$element "; } op: One Two ThreeBreak: switch statement without break
It is not essential to break out of all cases of a switch statement. But if you want that only one case to be executed, you have to use break statement.
$car = 'Mercedes Benz'; switch ($car) { default: echo '$car is not Mercedes BenzBreak: using optional argument
'; case 'Orange': echo '$car is Mercedes Benz'; } op: $car is not Mercedes Benz $car is Mercedes Benz
The break accepts an optional numeric argument, which describes how many nested structures it will exit. The default value is 1, which immediately exits from the enclosing structure.
$i = 0; while (++$i) { switch ($i) { case 5: echo "At matched condition i = 5
\n"; break 1; // Exit only from the switch. case 10: echo "At matched condition i = 10; quitting
\n"; break 2; // Exit from the switch and the while. default: break; } } op: At matched condition i = 5 At matched condition i = 10; quitting
The PHP continue statement is used to continue the loop. It continues the current flow of the program and skips the remaining code at the specified condition.
The continue statement is used within looping and switch control structure when you immediately jump to the next iteration.
The continue statement can be used with all types of loops such as - for, while, do-while, and foreach loop. The continue statement allows the user to skip the execution of the code for the specified condition.
Syntaxjump-statement; continue;Continue Example with for loop
In the following example, we will print only those values of i and j that are same and skip others.
//outer loop for ($i =1; $i<=3; $i++) { //inner loop for ($j=1; $j<=3; $j++) { if (!($i == $j) ) { continue; //skip when i and j does not have same values } echo $i.$j; echo ""; } } op: 11 22 33continue Example in while loop
In the following example, we will print the even numbers between 1 to 20.
//php program to demonstrate the use of continue statement echo "Even numbers between 1 to 20: "; $i = 1; while ($i<=20) { if ($i %2 == 1) { $i++; continue; //here it will skip rest of statements } echo $i; echo ""; $i++; } op: Even numbers between 1 to 20: 2 4 6 8 10 12 14 16 18 20continue Example with array of string
The following example prints the value of array elements except those for which the specified condition is true and continue statement is used.
$number = array ("One", "Two", "Three", "Stop", "Four"); foreach ($number as $element) { if ($element == "Stop") { continue; } echo "$element "; } op: One Two Three Fourcontinue Example with optional argument
The continue statement accepts an optional numeric value, which is used accordingly. The numeric value describes how many nested structures it will exit.
//outer loop for ($i =1; $i<=3; $i++) { //inner loop for ($j=1; $j<=3; $j++) { if (($i == $j) ) { //skip when i and j have same values continue 1; //exit only from inner for loop } echo $i.$j; echo ""; } } op: 12 13 21 23 31 32
Total : 26654
Today :3
Today Visit Country :