Creating an IF ELSE statement with PHP

Creating an IF ELSE statement with PHPThe if else statement in my mind, is one of the most commonly occurring PHP devices and has thousands of uses. If you’re not sure what an if else statement is, well I’d explain it quite simply in this way: “If the weather is cold, then wrap up warm, else where a T-shirt.”. As you can see, there is a condition to that statement.

Examples of if else statements

Take a look below at the same example, but in PHP:

$weather = "warm";
if($weather == "warm")
{ echo "Where a T-shirt."; }
else
{ echo "Wrap up warm."; }

The presence of the double ‘==’ means that the two values must completely match.¬†You could try an if else statement with numbers:

$number = 10;
if($number == 10)
{ echo "The number is ten"; }
else
{ echo "This number is not ten!"; }

The else offers an option to do something else if the first argument fails.

Now try the following. We can use greater than (>) or lesser than (<) within our if else statement.

$number = 7;
if($number >= 5)
{ echo "The number is equal or greater than 5."; }

The argument above reads: if number is greater or equal to 5. We could also omit the ‘=’ if we wanted the argument to pick up on only larger numbers.

We can also extend the if else statement for more complex arguments with the use of ‘elseif’:

$name = "John";
if($name == "Sarah")
{ echo "Hello Sarah."; }
elseif($name == "Peter")
{ echo "Hello Peter."; }
elseif($name == "John")
{ echo "Hello John."; }
else { echo "Hello, whoever you are!";}

How about adding to the argument:

$name = "Sarah";
if($name == "Sarah" || $name == "Peter"))
{ echo "You are either Sarah or Peter."; }

The ‘||’ represents ‘or’ and you can add as many of these connectors as you like within your if statement. To implement an ‘and’ try the following:

$price = "240";
$size = "25";
if($price < 250 && $size > 20))
{ echo "I think I have found what you are looking for"; }
else { echo "Nope, nothing here"; }

Notice the use of “” within our statements. Generally, you use quotation marks on words, sentences and sequences of numbers. You don’t need to add quotation marks on single part numbers.

Leave a Reply

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