PHP crash course : Conditionals, Loops and Functions
Tags: php, backends, tutorial, beginners
Published: 2022-01-23 18:02:50

---
title: PHP crash course : Conditionals, Loops and Functions
published: true
description: 
tags: php, backends, tutorial, beginners
cover_image: https://dev-to-uploads.s3.amazonaws.com/uploads/articles/nsa674115akg9vavf34n.jpg
series: ModernPHP
---
Today you will learn conditionals, loops and functions création in PHP.

This PHP crash course is free and will be posted here on dev.to. I'll be releasing a new article/post every two days or so. To not miss anything, you can follow me on twitter: <a href="https://twitter.com/EricTheCoder_" class="twitter-follow-button" data-show-count="false">Follow @EricTheCoder_</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>

# Conditional execution

In PHP, it is possible to execute a line of code only if a condition is true

```php
if ($name === 'Mike') {
    echo 'Hello Mike';
}
```

The code enclosed in the parentheses is called an expression. PHP will execute this code and return its boolean value (true or false).

If the result is 'true' then the code contained between the { } will be executed.

If the result is false, nothing will be executed in this if block

Here is another example with the operator greater than « > »

```php
$amount = 120;

if ($amount > 100) {
    echo 'Free shipping';
}
```

Here the expression ($amount) will return true, so shipping will be free.

It is possible to execute code if the condition is false

```php
$amount = 120;

if ($amount > 100) {
    echo 'Free shipping';
} else {
    echo 'Shipping 9.95$';
}
```

Here the keyword else executes the code if the expression is 'false'

Finally, it is possible to have several conditions

```php
$amount = 120;

if ($amount > 100) {
    echo 'Free shipping';
} elseif ($amount > 50) {
    echo 'Shipping 9.95$';
} else {
    echo 'Shipping 19.95$';
}
```

The elseif keyword is used to test another condition. Note that this condition will be tested only if the first condition is false.

If both the first and the second condition are false, then the code in the else section will be executed.

### Comparison operator

Here are the different operators that can be used in expressions.

==   equal no type check
===  equal with type check
!=   not equal
||   or
&&   and
\>   greater than
\<   less than

it is possible to test several expressions at the same time with the operator &&

```php
if ($amount > 0 && $amount < 50) {
   echo 'The price is between 1 and 49';
}
```

The same principle applies for the operator or ||

```php
if ($amount === 100 || $amount === 200) {
   echo 'The price is 100$ or 200$';
}
```

Expressions without a comparison operator

```php
$amount = 0;

if ($amount) {
    echo 'The price is not zéro';
}
```

Here the expression ($amount) does not contain a comparison operator, despite this fact, this code is valid. Why ? In PHP each expression is converted into a Boolean value. So here 0 is converted to false. Any other value other than zero (or null) would convert to true.

### Conversion to boolean value

Here is the list of values that will be converted to false 

false

0

0.0

null

‘0’ (string equal to zero)

‘ ’ (empty string)

[ ] (empty array)

All other values will convert to true

### Here are some examples of conversion to boolean value

```php
$messsage = 'Hello World'

if ($message) { // true
   echo $messsage;
}
```

```php
if ($value) {
    echo 'Variable is set';
} else {
    echo 'Variable is unset';
}
```

### Using IF statement in an HTML file

```html
<html lang="en">

<body>
    <?php $isAdmin = true; ?>

    <h1>Home page</h1>

    <?php if ($isAdmin) : ?>
        <p>Welcome Administrator</p>
    <?php else : ?>
        <p>Welcome Guest</p>
    <?php endif ?>

</body>

</html>
```
Each block of PHP code has an opening and closing tag. The particularity here is the “if” and “else” code block. There's no  { }. You can use “:” instead.

### Switch

If we have several conditions, the if, elseif ect. can result in hard-to-read code. In this case, the Switch statement helps to simplify your code.

```php
switch ($color) {
    case 'red':
        echo 'Danger';
         break;
    case 'yellow':
        echo 'Warning';
        break;
    case 'green':
        echo 'Success';
        break;
    default:
        echo 'The color is unknown';
}
```

The first line represents the expression we want to evaluate: switch($color)

Then just include the possible “cases”.

The “break” function prevents the execution from continuing

The “case” default is used if there is no matching case.

### Match

New in PHP 8.1, this instruction allows you to return an expression according to a key ⇒ value correspondence

```php
$type = match($color) {
    'red' => 'danger',
    'yellow', 'orange' => 'warning',
    'green' => 'success',
    default => 'Unknown'
};
```

The first line represents the expression we want to match: **match**($color)

On the second line we notice that it is possible to match more than one expression at a time.

Then follows a list of **key** ⇒ **value**. If no **key**→**value** is found, the **default** key will be executed.

Note that the key can be an expression and the value can also be an expression and even a function

```php
$type = match($color) {
    userID == 100 => openAdmin(),
    userID < 100 && userID > 0 => openUser(),
    default => openOther()
};
```

### Switch ou Match ?
**Match** is visually simpler but **Switch** allows to execute more than one line of code for each “box”. **Match** returns a value which **Switch** does not. In short, I use **Match** if possible because I find the instruction more visually refined but otherwise I have no problem with the **Switch** instruction

### Ternary operator  ?:

This is a shorthand syntax for an if...else.

Here is an example with if...else

```php
if ($isValid) {
    echo 'user valid';
} else {
    echo 'user not valid';
}
```

Here is the same example but with the Ternary operator

```php
echo $isValid ? 'user valid' : 'user not valid';
```

If the expression preceding the operator “?” is true then the value following “?” will be used, otherwise the value following the “:” will be used.

### The null coalescing operator ??

The Null coalescing operator returns its first operand if it exists and is not NULL; otherwise it returns its second operand

```php
echo $name ?? 'Mike';  //output 'Mike' if $name is null
```

### Assignment with Null coalescing operator ??

```php
$name ??= 'Mike';
```

Assigns the value 'Mike' if the variable $name is null

### Null safe operator

```php
echo $user?->profile?->activate();
```

If one of the variables preceding the “?” is null then the value of of the expression will be null


# Loops

### The “while” loop
Allows a block of code to be executed a certain number of times. The number of times will depend on the conditions. As long as the condition is true, the code block will run.

```php
$number = 1;
while ($number < 10) {
    echo 'value : ' . $number ;
    $number += 1;
}
```

Here the code block will be executed 9 times.

### “do while” loop

Essentially the same principle as the “while” loop, but in this case the block of code will always execute at least once. The condition being tested only at the end of the code block.

```php
$number = 1;
do {
    echo 'value : ' . $number ;
    $number += 1;
} while ($number < 10);
```

### The “for” loop

Used to execute a block of code a number of times defined by a condition.

```php
for ($i = 0; $i < 20; $i++) {
    echo "i value = " . i;
}
```

The parameter is divided into three sections, the first being the definition of the counter ($i = 0). Then the condition to respect to execute the block of code ($i < 20) and finally the code to execute at each iteration ($i++)

### The “foreach” loop

The foreach function executes a block of code for each element of an array.

```php
$names = ['Mike', 'Shawn', 'John'];

foreach($names as $name) { 
   echo 'Hello ' . $name;
}
```

The first parameter is the name of the array to browse, the second parameter represents the reference to the current element.

### Break and Continue

The break and continue statements are used to modify the loop

```php
for ($i = 0; $i < 20; $i++) {
    if ($i % 2 === 0) {
        continue;
    }
    echo $i . '<br>';
}
```

This loop will print the value of $i, only when the value is odd.

If the value is even ($i % 2 === 0). So we ask the loop to do a **continue** with the next value.

It is possible to exit the loop at any time with the **break** instruction

```php
$i = 0;

while ($i < 10000) {
    $i++;
    if ($i == 10) {
        break;
    }
    echo $i . '<br>';
}
```

Here the loop will stop when $i will have 10 as value

# Functions
In PHP there are several functions already pre-defined. It is also possible to create our own functions.

Functions allow us to avoid repeating our code several times. They also allow us to divide our application into small pieces that are easier to maintain.

The syntax for creating a function is quite simple

```php
function hello() {
    echo 'Hello World';
}
```

Here we use the keyword “function” followed by the name of our function.

Once our function has been created, it is possible to launch its execution

```php
hello();
```

It is possible to include one or more parameters to our function

```php
function hello($firstName, $lastName) {
    echo 'Hello' . $firstName . ' ' . $lastName;
}
```

The launch of the function must include the parameters in the order they were declared

```php
hello('Mike', 'Taylor');
```

A default value can be assigned to a parameter which suddenly makes this parameter optional when calling the function.

```php
function hello($firstName, $lastName = 'none') {
    echo 'Hello' . $firstName . ' ' . $lastName;
}

hello('Mike');
// Mike none
```

Note that parameters with a default value must absolutely be defined last.

Since version 8 of PHP it is possible to launch a function by naming the parameters. The call is clearer and the order of the parameters does not have to be respected.

```php
hello(lastName: 'Taylor', firstName: 'Mike');
```

### Return

Returns a value when calling the function.

```php
function fullName($firstName, $lastName) {
    return $firstName . ' ' . $lastName;
}

echo fullName('John', 'Doe');
```

Here the function returns a concatenated string with first name and last name

The echo function will display on the web page the value returned by the fullName() function

### Anonymous functions (closure)

Allows the creation of functions without specifying their name. Here is an example :

```php
$sum = function ($a, $b) (
    return $a + $b;
);

echo $sum(10, 15);
```

Anonymous functions end with a semicolon; And they can't access the parent context variables.

It is possible to pass a variable from the parent context with the statement **use**

```php
$x = 10;

$sum = function ($a, $b) use $x (
    return $x + $a + $b;
);

echo $sum(10, 15);
// 35
```

### Callback functions

Callback functions are anonymous functions passed as parameters. here is an example

```php
$products = ['iPhone 12', 'iPhone 13', 'iPad', 'iWatch'];

$filtered_products = array_filter($products, function ($product) {
    return str_contains($product, 'Phone');
});

print_r($filtered_products);
// Array ( [0] => iPhone 12 [1] => iPhone 13 )
```

Here the array_filter() function has an anonymous function as second parameter.

### Arrow functions

Allows the use of a shortcut syntax:

```php
$products = ['iPhone 12', 'iPhone 13', 'iPad', 'iWatch'];

$filtered_products = array_filter($products, fn ($product) => str_contains($product, 'Phone'));

print_r($filtered_products);
```

Note that for the moment, the Arrow functions allow the execution of only one expression. Arrow functions are executed in the current context so they can use variables without having to use the **use** statement.

### Function Type Hint

Note that functions can be typed (string, int, etc.). It is possible to define a type for each of the parameters and a type for the return value of the function

```php
function display(string $first, string $last) : string {
    return "$first $last";
}
```

Here the $first and $last parameters must be of type string as well as the return value.

There are several other things to know about typed functions, we will come back to this later.

### Strict Type

Here is an example of a function with type

```php
function add(int $a, int $b): int
{
    return $a + $b;
}

echo add('10', 20);
// 30
```

In this example the parameter $a is of type integer. However PHP does not return an error. The reason is that PHP will try to convert the string '10' to an integer. If the conversion is possible then no error is reported.

There are times when you would like PHP to not allow this conversion and only execute if the parameter is really of the specified type. To do this you must add an instruction at the beginning of your file.

```php
declare(strict_types=1);

function add(int $a, int $b): int
{
    return $a + $b;
}

echo add('10', 20);
// TypeError
```

Here an error is returned because the type of the parameter is not an integer

## Conclusion
That's it for today, I'll be releasing a new article every two days or so. To be sure not to miss anything you can follow me on twitter: <a href="https://twitter.com/EricTheCoder_" class="twitter-follow-button" data-show-count="false">Follow @EricTheCoder_</a><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script>