5. Conditionals

Conditionals are an essential tool in any programming language. They serve to execute instructions depending on certain conditions.

if (condición) {
    ...
}

In the example you can see that inside the if I am asking a question: is 2 greater than 0? It is true, therefore the second echo will be printed.

echo "Start \n";
if (2 > 0) {
    echo "I enter the conditional \n";
}
echo 'End';
// Start
// I enter the conditional
// End

In case it is never met, it will not enter: is 2 greater than 1000? It is false, therefore it will never be executed.

echo "Start \n";
if (2 > 1000) {
    echo "I enter the conditional \n";
}
echo 'End';
// Start
// End

Types of conditionals

Conditionals are arithmetic symbols. If the logic is true, it will enter. Otherwise it will not be met and the inside of the if or while (both use conditionals) will never be executed. In addition, we can chain together all the conditionals we need. The use of parentheses is allowed.

Symbol Explanation Example
> is greater than if (1 > 0)
< is less than if (1 < 0)
&& and if (1 > 0 && 67 > 0)
|| or if (1 > 10 || 67 > 0)
! not if (!(1 > 0))
== is equal in value if ('3' == 3)
=== is equal in value and type if ('3' === '3')
!= is not equal if ('Doctor' != 'Who')
!== is not equal in value or type if ('Doctor' !== 'Who')
>= is greater than or equal to if (10 >= 10)
<= is less than or equal to if (10 <= 20)
<=> -1, 0 and 1 depending on whether the values are exceeded (10 <=> 20) // 1
True True if (True)
False False if (False)
if (10 > 2 && True && 'HBO' != 'Netflix') {
    echo 'I enter for sure';
}
// I enter for sure

else

There is a tool that will help us make only a certain set of instructions run.

if (condición) {
    ...
} else {
    ...
}

If the condition is met, it will enter the first braces ({}); otherwise it will enter the second braces. But never both.

if ('Ghibli' == 'Ghibli') {
    echo 'Welcome';
} else {
    echo 'You are not welcome'
}
// Welcome
if ('Estudio' == 'Ghibli') {
    echo 'Welcome';
} else {
    echo 'You are not welcome'
}
// You are not welcome

elseif

It is possible to have several conditionals.

if (condición) {
    ...
} elseif (condición) {
    ...
}
if ('Michael Jackson' == 'Moonwalker') {
    echo 'Great dance';
} elseif ('Moonwalker' == 'Moonwalker') {
    echo 'Legendary';
}
// Legendary

If the first one is met, it will enter and ignore the second. If the first one is not met but the second one is, it will enter the second. If neither is met, it will not enter any.

By adding an else at the end, we give it a "default" case. If no conditional were met, it would go there automatically.

if (condición) {
    ...
} elseif (condición) {
    ...
} else {
    ...
}
if ('Michael Jackson' == 'Moonwalker') {
    echo 'Great dance';
} elseif ('Michael Jackson' == 'Billie Jean') {
    echo 'Great song';
} else {
    echo 'King of Pop';
}
// King of Pop

Both elseif and else if are allowed. Except in the alternative syntax, where it must be together: elseif:.

Alternative syntax

To make integration with HTML easier, you have an alternative syntax that is a bit more pleasant to the eye.

<html>
    <body>
    <?php if (condición): ?>
    // Code that is true
    <?php else: ?>
    // Code that will be executed if it is not true.
    <?php endif; ?>
    </body>
</html>

or with an elseif.

<html>
    <body>
    <?php if (condición): ?>
    // Code that is true
    <?php elseif (condición): ?>
    // Code that will be executed if it is not true.
    <?php else: ?>
    // Code that will be executed if it is not true.
    <?php endif; ?>
    </body>
</html>

Shorthand form (Ternary operator)

It is possible to execute an if with an else in a single instruction. If you are just starting out I do not recommend using it, but do not forget it.

<?php (condicional) ? 'Valor si se cumple' : 'Valor si no se cumple'; ?>
<?php echo (5 > 10) ? 'It is true' : 'It is false'; ?>

Null Coalescing operator (??)

Introduced in PHP 7.0, the ?? operator is an elegant way to check whether a variable exists and is not null. If the variable exists and is not null, it returns its value; otherwise it returns the default value.

// Old way
$nombre = isset($_GET['nombre']) ? $_GET['nombre'] : 'Invitado';

// Modern way (PHP 7.0+)
$nombre = $_GET['nombre'] ?? 'Invitado';

It is especially useful for forms and GET/POST parameters:

$edad = $_POST['edad'] ?? 18;
$email = $_GET['email'] ?? 'sin-email@example.com';

There is also the null coalescing assignment operator ??= (PHP 7.4+):

$config['timeout'] ??= 30; // Only assigns if it does not exist or is null

Switch

The functionality of switch is practically the same as if, except that it is more limited: it only supports the equality conditional.

switch ($variable) {
    case 0:
        ...
        break;
    case 1:
        ...
        break;
    case 2:
        ...
        break;
    default:
        ...
        break;
}

An equivalence between the two.

$num = 1;
if ($num == 0) {
    echo "num is equal to 0";
} elseif ($num == 1) {
    echo "num is equal to 1";
} elseif ($num == 2) {
    echo "num is equal to 2";
} else {
    echo "I don't know what it is equal to";
}
// num is equal to 1

switch ($num) {
    case 0:
        echo "num is equal to 0";
        break;
    case 1:
        echo "num is equal to 1";
        break;
    case 2:
        echo "num is equal to 2";
        break;
    default:
        echo "I don't know what it is equal to";
        break;
}
// num is equal to 1

Match (PHP 8.0+)

The match expression is a modern and improved alternative to switch, introduced in PHP 8.0. It has several important advantages:

  1. It returns a value (it is an expression, not a statement)
  2. It uses strict comparison (===) instead of loose comparison (==)
  3. It does not require break (there is no fall-through)
  4. It throws an error if there is no match (unless there is a default)
$resultado = match($num) {
    0 => "num is equal to 0",
    1 => "num is equal to 1",
    2 => "num is equal to 2",
    default => "I don't know what it is equal to"
};
echo $resultado;
// num is equal to 1

You can combine multiple values in the same case:

$mensaje = match($status) {
    200, 201, 202 => 'Success',
    400, 401, 403 => 'Client error',
    500, 502, 503 => 'Server error',
    default => 'Unknown status'
};

Unlike switch, match uses strict comparison:

$valor = '1';

// switch uses == (loose comparison)
switch ($valor) {
    case 1:
        echo 'Enters here'; // It runs because '1' == 1
        break;
}

// match uses === (strict comparison)
$resultado = match($valor) {
    1 => 'Does not enter here', // It does not run because '1' !== 1
    '1' => 'Enters here', // It runs because '1' === '1'
};

Strings

Before closing the lesson, I want to leave you some functions that can be helpful when you work with String. We will go deeper in the following lessons.

str_contains (Does this text contain this other text?)

if (str_contains('La duda es uno de los nombres de la inteligencia', 'duda')) {
    // Enters
}

str_starts_with (Does this text start with this other text?)

if (str_starts_with('La duda es uno de los nombres de la inteligencia', 'La duda es')) {
    // Enters
}

str_ends_with (Does this text end with this other text?)

if (str_ends_with('La duda es uno de los nombres de la inteligencia', 'inteligencia')) {
    // Enters
}
Activity 1
  • Build a form with the following data: name, phone, email and message.
  • When send is clicked, it must show the following template.

"Hello name!

I am going to send you spam to email and I will call you in the early morning at phone.

message

Sent from an iPhone"

Activity 2

1. Write a list of names in a textarea.

2. When you press a button, it must show a random name. (They will be in charge of walking the dog)

3. Show it with the following template: name walks the dog.

Example in textarea:

Batman

Superman

Ironman

Pescanova

When the button is pressed...

Ironman walks the dog.

Activity 3
  • Show the following riddle:

"This thing all things devours;

Birds, beasts, trees, flowers;

Gnaws iron, bites steel;

Grinds hard stones to meal;

Slays king, ruins town,

And beats high mountain down."

  • In an input, ask for the answer.
  • Add a submit button.
  • If the button is pressed, you must check whether they got it right. The answer is: Time.
  • If they get it right, congratulate them.
  • If they lose, show the answer and devour them.
Activity 4
  • Build a VAT calculator again, but this time the amount will not be stored in a variable; instead the user will provide it to us.

Hint: To calculate the VAT you must apply the following formula price / 1.21.

Activity 5
  • Create an input and a submit button.
  • Fill the field with the name of a movie.
  • When it is pressed, it must store the content in an array.
  • Print the result in a table.
Activity 6
  • Build an array or dictionary with some students and their respective grades.

Marta: 7,8

Luis: 5

Lorena: 6,9

...

  • Show the grades in an orderly way.
Student Grade
Marta 7,8
Luis 5
  • Give the option to add new students.

Pro:

  • Show the average at the bottom.
Activity 7

To get on the ride we are going to build a validator that minimizes the fatalities. To do this we will use several requirements.

  • They must be taller than 120cm.
  • They must be older than 16 years.
  • Do they refuse to take us to court for damages caused by poor maintenance?

If everything is valid, we will give them the ticket.

Pro:

  • Generate a ticket with their name and a unique number. Example: "Alfonso, ticket 00034".
Activity 8
  • Ask for the name.
  • Ask for the sex.
  • Ask for the number of children.
  • Show the following sentence depending on the previous data:

Mr. Pepe has 1 child.

Mr. Pepe has 4 children.

Mrs. Sonia has 1 child.

Mrs. Sonia has no children.

This work is under a Attribution-NonCommercial-NoDerivatives 4.0 International license.

Desafíos de programación atemporales y multiparadigmáticos

Desafíos de programación atemporales y multiparadigmáticos

Te encuentras ante un librillo de actividades, divididas en 2 niveles de dificultad. Te enfrentarás a los casos más comunes que te puedes encontrar en pruebas técnicas o aprender conceptos elementales de programación.

Buy the book

Will you buy me a coffee?

This is how I keep writing without ads or paywalls.

Comments

There are no comments yet.