Learning PHP – Lesson 3 – if … else

Views: 23
0 0
Read Time:7 Minute, 8 Second

In this lesson we are going to look at how to execute some code under a condition or another by presenting the PHP if, else, elif, else if constructs. These are constructs that allow to execute some code under specific conditions or other code, or other code … or some other code… depending on which one of these conditions (expressions) will be evaluated true.

Learning PHP – Introduction

Learning PHP – print and echo

Learning PHP – The variables

Learning PHP – if else

Learning PHP – Arrays

Learning PHP – The loops

Learning PHP – The Functions

The comparison operators

Before looking at how the if/else area being used we need to introduce the comparison operators that will help us to compare values/expressions and so on. In PHP we have the binary operators for doing a dual comparison (i.e. my cat is bigger than yours $my_cat > $your_cat) and the unary operator that will be the negation of the expression we want to evaluate using the ! in front (i.e. !$a == True)

OperatorMeaningExample where this can be evaluated as true
>greater than3 > 2
>=greater or equal3 >= 2 or 3 >=3
<smaller2 < 3
<=smaller or equal 2 <= 3 or 3 <= 3
==equal2 == 2, 1 == 1
===equal and identicalThis will check that the two values are equals
but also that the type is identical.
<=>The spaceship(this took me a while to absorb when was out)
An int less than, equal to, or greater than zero when $a is less than, equal to, or greater than $b, respectively.

Some examples

<?php

$a = 1;
$b = 2;
$c = '1';
$d = 1;

var_dump($a > $b); // false
var_dump ($a >= $b); // false
var_dump ($a < $b) ; // true
var_dump($a <= $b); // true
var_dump($a == $b); // false
var_dump ($a == $c); // true
var_dump ($a == $d); // true
var_dump ($a ===  $b); // false
var_dump ($a ===  $c); // false
var_dump ($a ===  $d); // true
var_dump ($a <=> $b);

// spaceship time
var_dump($a <=> $b); // -1
var_dump($a <=> $c); // 0
var_dump($a <=> $d); // 0
var_dump($b <=> $d); // 1
?>

It is important to note that the == operator will evaluate the int 1 equals to the string ‘1’ or “1” but this evaluation will be false using the === operator because will check not only the value but also the type, that in our example will be an int and a string.

The if

As we were saying above, the if construct is used to execute some code under particular circumstances and these circumstances are the result of the expression evaluation. It is used in this way

// example 1
if ( expression )
    //do something
// example 2
if ( expression ) {
    //do something
}
// example 3
if ( expression ) { /* do something */ }

A small example

<?php

  $var1 = 1;
  $var2 = 2;
  if ( $var1 > $var2 )
    echo "$var1 is greater than $var2\n";
  if ( $var1 < $var2)
    echo "$var1 is smaller than $var2\n";
  echo "End of the execution\n";

?>

If you try to execute nothing should surprise you. The above example could also be written as below by using the graphs { } .

<?php

  $var1 = 1;
  $var2 = 2;
  if ( $var1 > $var2 ) { echo "$var1 is greater than $var2\n"; }
  if ( $var1 < $var2 ) { echo "$var1 is smaller than $var2\n"; }              

  echo "End of the execution\n";

?>

We could also write the same using the else

The else

The else is an extension of the if statement and is working in an exclusive way. See the example below

<?php

  $var1 = 1;
  $var2 = 2;
  if ($var1 > $var2)
    echo "$var1 is greater\n";
  else
    echo "$var2 is greater\n";

?>

Let’s look instead a this example

<?php
  
  $var1 = 1;
  $var2 = 2;
  if ( $var1 == $var2 )
    echo "the 2 values are the same\n";
  else
    echo "$var1 is smaller than $var2\n";
  echo "End of the execution\n";

?>

The above example could make sense up to a certain point but this is to show you that when we have the if else construct, as soon the first expression in the if is evaluated as false, all the execution will fall into the else. If we want to make more than 1 expression evaluation we can use the elif/else if statements

The elif/else if

This statements are one the alias of the other and as the names suggests are just a combination of if else. See the example below

<?php
  $var1 = 1;
  $var2 = 2;
  if ( $var1 > $var2 )
    echo "$var1 is greater\n";
  elseif ($var1 < $var2)
    echo "$var1 is smaller\n";
  else
    echo "they are the same\n";
  echo "End of the execution\n";
?>

It is important to note that when if/elseif/else are being used in chain like the example above, only 1 of code blocks will be executed and as soon is completed the execution will go to the last echo outside the if/elseif/else control.

Nesting

All the above if/elseif/else can be used in a nested format, that means that we can use if/else within other if/else (I would discourage you to use that unless is really needed because it makes the code unreadable), see the example below

<?php
  $var1 = 1;
  $var2 = 2;
  $var3 = 4;
  $colour1 = 'orange';
  $colour2 = 'black';

  if ($var1 > $var 2)
    if ($colour1 == 'orange')
      echo "$var1 is greater and the colour is orange\n";
    elseif ($colour2 == 'black')
      echo "$var1 is greater and the colour is black\n";
  elseif ($var1 <= $var2)
    if ($colour1 == 'orange')
      if ($var1 == $var2)
        echo "the colour is orange and var1 = var2\n";
      else 
        echo "the colour is orange and var1 < var2\n";
    elseif ($colour1 == 'black')
      if ($var1 == $var2)
        echo "the colour is black and var1 = var2\n";
      else 
        echo "the colour is black and var1 < var2\n";
  else
    echo "I'm lost\n";
?>   

right…headaches, and will be very difficult to find bugs, so as reminder, keep the code easy to read, if not possible use meaningful variable names and add comments. There is one last if statement that is very handy in PHP

The inline if

This is called the ternary operator and is a very handy alternative to the if/else statements. It is presented in this way

(expression) ? (statement 1) : (statement 2); 

If expression is evaluated as true then (statement1) is being executed, else (statement2)

See the example below

<?php

  $var1 = 1;
  $var2 = 2;
  echo ($var1 > $var2) ? "var1 greater" : "var2 greater";

?>

It is very handy when we need to assign values to variables as output of an if/else. The two examples below produce the same result

<?php  

  $var1 = 1;
  $var2 = 2;
  $greater = '';

  //example 1
  if ($var1 > $var2)
    $greater = $var1;
  else
    $greater = $var2;

  //example 2
  $greater = ($var1>$var2) ? $var1 : $var2;
  echo "the greater is $greater\n";

?>

Bonus section the PHP ?? operator

The ?? is the Null coalescing operator, it is available only from PHP7 and was introduced when the ternary operator was needed in conjunction with the isset function (we will see this in future lessons). It is used as below

$variable = expression1 ?? epxression2

This is super handy and will remove a lot of potential bugs in advance when used correctly because is forcing to have values associated to variables. We will came back on this when we will introduce the functions but for now it can be used as below

<?php

  $var1 = 1;
  $var2 = 2;

  $value = ($var1) ?? $var2;
  echo "the value is $value"

?>

The output of the above will be “The value is 1”, but let’s look at the below example

<?php

  $var1;
  $var2 = 2;

  $value = ($var1) ?? $var2;
  echo "the value  is $value"

?>

It is not surprising that the output is “The value is 2” but what is happening behind the scenes is that $var1 is checked to see if is a variable defined AND has a value in it. Since in our case we just declared the variable but never assigned a value the ?? operator is returning the $var2 from the entire expression

($var1) ?? $var2

and this is associated to $value as part of the = operation. Not really intriguing so far, but we will return on this in one of the next articles.

Hope you enjoyed this article and if you really liked please share and help us grow!

Happy
Happy
0 %
Sad
Sad
0 %
Excited
Excited
0 %
Sleepy
Sleepy
0 %
Angry
Angry
0 %
Surprise
Surprise
0 %
Previous post Learning PHP – Lesson 2 – Learn the PHP variables
Next post Learning PHP – Lesson 5 – Learn how to use PHP Loops
0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x