Basics of php, if else, switch case, for loops, while loop
In this post we will learn the basics of php programming language#
below points we will cover in this post
- if condition
- switch case
- for loop
- while loop
As we know php is scripting language and it is server side it gives dynamic behaviour for creating html content. we can combine both html and php in single script.
filename for php file ends with .php
and code specific to php will be contained inside <?php //code ?>
tags.
simple php script will look like below
<body>
<h2> Hello this is from <?php echo "Php Script"; ?> </h2>
</body>
if we will run this script it will output like below
<body>
<h2> Hello this is from Php Script</h2>
</body>
Now lets create a if else block if the expression in if block will true then that if block will execute otherwise else block will execute.
$exp = (5 == 4);
if ($exp){
echo "5 is equal to 4";
} else {
echo "5 is not equal to 4";
}
we can have mulitple else block with if condition like below
if(expression){
} else if (expression){
} else if (expression){
} else if (expression){
} else {
}
Now let go to the switch case. switch case works little differente than if else , in if else it checks for expression output either true or false but in switch case it match the exact value with case and switch, and jumps to that case block.
In terms of performance switch is faster than if else so if possible to use switch case prefer that.
<?php
$val = "A";
switch($val) {
case "A":
echo "Value of variable is A";
break;
case "B":
echo "Value of variable is B";
break;
case "C":
echo "Value of variable is C";
break;
default:
echo "This is execute if no case matched.";
}
?>
As you can see in above example it is very clear that block is matching the value of $val variable which is passed in switch statement.
if no case matched then default block will execute if it is defined.