Browse By

if…else, Switch and loops in PHP

Spread the love

If … else

<?php
if (condition) {
    code to be executed if condition is true;
} else {
    code to be executed if condition is false;
}
?>
Example:
<?php
$x = 20;
if($x>10)
{
echo "$x is greater no.";?>
}else{
echo "$x is smaller no.";
}?>

Nested If

<?php

if($condition){
//your code
}else if($condition)
{
//your code
}
....
..
..
}else{
// default if no condition matches.
}?>

PHP switch Statement

<?php
$favno = "10";

switch ($favno) {
    case "5":
        echo "sorry your fav no. is not 5";
        break;
    case "8":
         echo "sorry your fav no. is not 8";
        break;
    case "10":
         echo "sorry your fav no. is 10";
        break;
    default:
         echo "sorry your fav no. is 10";
}
?>

It is used to perform action based of condition matches like if statement does but comparatively switch is faster then if statement.

Loops in PHP

To repeat some short of code is with basic icons is called loop.

PHP have 4 types of loops just like other language have

  1. while loop- basically used when you are not sure how much time will the loop run.
  2. do..while – same as above but in this loop condition will be checked after loop is executed once. if you want the loop to run once then this is best in practice.
  3. for – basically user for array or any no. of time you want to repeat things
  4. foreach – This loop is pure array element irritation loop.

while loop:

<?php
$x = 1;
while($x <= 5) {
    echo "The number is: $x <br>";
    $x++;
}
?>

Do while loop:

<?php
$x = 1;

do {
    echo "The number is: $x <br>";
    $x++;
} while ($x <= 5);
?>

For Loop:

<?php
for ($x = 0; $x <= 10; $x++) {
    echo "The number is: $x <br>";
}
?>

foreach Loop:

<?php
$age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

foreach($age as $x => $val) {
  echo "$x = $val<br>";
}
?>

Leave a Reply

Your email address will not be published. Required fields are marked *