PHP Tutorials - If Statement

PHP handles If and IF/Else statements similar to all other programming languages.

IF / Else statements are known as Conditional statements and allow you to make choices based on a condition being true or false.

Here is the basic format of If/Else statements in PHP

Example:

<?php
$number = 3;
$firstName = "Fergal";

//evaluate a number
if($number == 3){
	echo " number is 3";
}else {
	echo " number is 4";
}

//evaluate a string
if($firstname == "fred"){
	echo " firstname is fred";
}else{
	echo " firstname is fergal.";
}
?>


The main thing you need to remember is when handling strings you have to include inverted commas.

Ok so now lets look at the code We have created two variables $number and $firstname and we have assigned them some values like below.

<?php
$number = 3;
$firstName = "Fergal";
?>

Next in our if statement we compared a variable to an integer,
- if($number == 3) Note: "==", which in English means "Is Equal To".

What we are saying in real life is if(3 is equal to 3) which evaluates to TRUE then output

number is 3.

Now lets test our string condition

<?php
$firstName = "Fergal";
//evaluate a string
if($firstname == "fred"){
	echo " firstname is fred";
}else{
	echo " firstname is fergal.";
}
?>



The output here is clearly Fergal and $firstname is not equal to fred thus result is FALSE so we execute the else part of statement.


php if else tutorial