PHP crash course : Conditionals, Loops and Functions

ericchapman

Eric The Coder

Posted on January 23, 2022

PHP crash course : Conditionals, Loops and Functions

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: Follow @EricTheCoder_

Conditional execution

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

if ($name === 'Mike') {
    echo 'Hello Mike';
}
Enter fullscreen mode Exit fullscreen mode

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 « > »

$amount = 120;

if ($amount > 100) {
    echo 'Free shipping';
}
Enter fullscreen mode Exit fullscreen mode

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

It is possible to execute code if the condition is false

$amount = 120;

if ($amount > 100) {
    echo 'Free shipping';
} else {
    echo 'Shipping 9.95$';
}
Enter fullscreen mode Exit fullscreen mode

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

Finally, it is possible to have several conditions

$amount = 120;

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

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 &&

if ($amount > 0 && $amount < 50) {
   echo 'The price is between 1 and 49';
}
Enter fullscreen mode Exit fullscreen mode

The same principle applies for the operator or ||

if ($amount === 100 || $amount === 200) {
   echo 'The price is 100$ or 200$';
}
Enter fullscreen mode Exit fullscreen mode

Expressions without a comparison operator

$amount = 0;

if ($amount) {
    echo 'The price is not zéro';
}
Enter fullscreen mode Exit fullscreen mode

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)

All other values will convert to true

Here are some examples of conversion to boolean value

$messsage = 'Hello World'

if ($message) { // true
   echo $messsage;
}
Enter fullscreen mode Exit fullscreen mode
if ($value) {
    echo 'Variable is set';
} else {
    echo 'Variable is unset';
}
Enter fullscreen mode Exit fullscreen mode

Using IF statement in an HTML file

<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>
Enter fullscreen mode Exit fullscreen mode

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.

switch ($color) {
    case 'red':
        echo 'Danger';
         break;
    case 'yellow':
        echo 'Warning';
        break;
    case 'green':
        echo 'Success';
        break;
    default:
        echo 'The color is unknown';
}
Enter fullscreen mode Exit fullscreen mode

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

$type = match($color) {
    'red' => 'danger',
    'yellow', 'orange' => 'warning',
    'green' => 'success',
    default => 'Unknown'
};
Enter fullscreen mode Exit fullscreen mode

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 keyvalue. If no keyvalue 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

$type = match($color) {
    userID == 100 => openAdmin(),
    userID < 100 && userID > 0 => openUser(),
    default => openOther()
};
Enter fullscreen mode Exit fullscreen mode

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

if ($isValid) {
    echo 'user valid';
} else {
    echo 'user not valid';
}
Enter fullscreen mode Exit fullscreen mode

Here is the same example but with the Ternary operator

echo $isValid ? 'user valid' : 'user not valid';
Enter fullscreen mode Exit fullscreen mode

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

echo $name ?? 'Mike';  //output 'Mike' if $name is null
Enter fullscreen mode Exit fullscreen mode

Assignment with Null coalescing operator ??

$name ??= 'Mike';
Enter fullscreen mode Exit fullscreen mode

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

Null safe operator

echo $user?->profile?->activate();
Enter fullscreen mode Exit fullscreen mode

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.

$number = 1;
while ($number < 10) {
    echo 'value : ' . $number ;
    $number += 1;
}
Enter fullscreen mode Exit fullscreen mode

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.

$number = 1;
do {
    echo 'value : ' . $number ;
    $number += 1;
} while ($number < 10);
Enter fullscreen mode Exit fullscreen mode

The “for” loop

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

for ($i = 0; $i < 20; $i++) {
    echo "i value = " . i;
}
Enter fullscreen mode Exit fullscreen mode

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.

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

foreach($names as $name) { 
   echo 'Hello ' . $name;
}
Enter fullscreen mode Exit fullscreen mode

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

for ($i = 0; $i < 20; $i++) {
    if ($i % 2 === 0) {
        continue;
    }
    echo $i . '<br>';
}
Enter fullscreen mode Exit fullscreen mode

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

$i = 0;

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

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

function hello() {
    echo 'Hello World';
}
Enter fullscreen mode Exit fullscreen mode

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

hello();
Enter fullscreen mode Exit fullscreen mode

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

function hello($firstName, $lastName) {
    echo 'Hello' . $firstName . ' ' . $lastName;
}
Enter fullscreen mode Exit fullscreen mode

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

hello('Mike', 'Taylor');
Enter fullscreen mode Exit fullscreen mode

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

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

hello('Mike');
// Mike none
Enter fullscreen mode Exit fullscreen mode

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.

hello(lastName: 'Taylor', firstName: 'Mike');
Enter fullscreen mode Exit fullscreen mode

Return

Returns a value when calling the function.

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

echo fullName('John', 'Doe');
Enter fullscreen mode Exit fullscreen mode

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 :

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

echo $sum(10, 15);
Enter fullscreen mode Exit fullscreen mode

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

$x = 10;

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

echo $sum(10, 15);
// 35
Enter fullscreen mode Exit fullscreen mode

Callback functions

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

$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 )
Enter fullscreen mode Exit fullscreen mode

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

Arrow functions

Allows the use of a shortcut syntax:

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

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

print_r($filtered_products);
Enter fullscreen mode Exit fullscreen mode

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

function display(string $first, string $last) : string {
    return "$first $last";
}
Enter fullscreen mode Exit fullscreen mode

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

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

echo add('10', 20);
// 30
Enter fullscreen mode Exit fullscreen mode

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.

declare(strict_types=1);

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

echo add('10', 20);
// TypeError
Enter fullscreen mode Exit fullscreen mode

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: Follow @EricTheCoder_

💖 💪 🙅 🚩
ericchapman
Eric The Coder

Posted on January 23, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related