PHP

PHP

For a short explanation about PHP, how it functions and / or for the Documentation you can find it here: PHP explanation

Generally PHP will be used for the backend so you won’t see most of the code that you actually write though at times you will have or want to display PHP code or logic and for that you will most likely use HTML. Tough it depends on what you want, if you only want the answer then you can just do it in PHP but if you want to see “Hello, World” for example on your page you will need HTML.

To include PHP code inside an HTML file you can’t do that directly you will need to put the PHP code between the opening tag “<?php” and the closing tag “?>” for PHP.

The first thing that you usually do in coding is write “Hello World” on your page or even just in the code, so that what well look at first in the echo chapter:

Table of contents

echo

The standard method to print out a simple text (string) depends on the language in JavaScript its “console.log("Hello, World");” or in Python its
“print("Hello, World")” but in PHP its “echo "Hello, World";“. Here are a few examples on how it may look in PHP:Ind

Example 1:

PHP
<h1>
    <?php 
        echo "Hello, World";
    ?>
</h1>

Example 2:

PHP
<h1>
    <?php
        echo "Hello, " . "World";
    ?>
</h1>

Example 3:

PHP
<h1>
    <?php
        $greeting = "Hello";
    
        echo "$greeting," . " " . "World";
    ?>
</h1>

Example 4:

PHP
<h1>
    <?php
        $greeting = "Hello";

        echo "$greeting, World";
    ?>
</h1>

All 4 examples give out the same output: “Hello, World“. “echo” is used to show / output strings.

if statement

Here are a few simple examples of if statements:

normal if statement:

PHP
<p>
  <?php
  if ($a > $b)
    echo "a is bigger than b";
  ?>
</p>

So this will check if the value stored in the variable “$a” is bigger than the one stored in “$b” if so it will output “a is bigger than b” and if that is not the case it will output nothing.

if statement with “else”:

PHP
<p>
  <?php
  if ($a > $b) {
    echo "a is greater than b";
  } else {
    echo "a is NOT greater than b";
  }
  ?>
</p>

So this will check if the value stored in the variable “$a” is bigger than the one stored in “$b” if so it will output “a is greater than b” and if that is not the case it will output “a is NOT greater than b“.

if statement with “elseif”:

PHP
<p>
  <?php 
  if ($a > $b) {
      echo "a is bigger than b";
  } elseif ($a == $b) {
      echo "a is equal to b";
  } else {
      echo "a is smaller than b";
  }
  ?>
</p>

So this will check if the value stored in the variable “$a” is bigger than the one stored in “$b” if so it will output “a is greater than b” then it will check if the value stored in “$a” is the same than in “$b” if so it will output “a is equal to b” and if that is not the case it will output “a is NOT greater than b“.

Though you will refrain from using “elseif” unless its a special exception instead you will use one of these: Match expression or Switch statement.

if statement with “and”:

PHP
<p>
  <?php 
  // example 1
  if ($a > $b && $a < 20) {
    echo "a is bigger than b and smaller than 20";
  }
  
  // example 2
  if ($a > $b and $a < 20) {
    echo "a is bigger than b and smaller than 20";
  }
  ?>
</p>

This will check if the value of “$a” is bigger than the one of “$b” and if “$a” is less than 20 meaning both will need to be true for it to output “a is bigger than b and smaller than 20“.

Both examples will work the same though it is recommended that you use “&&” since it has a greater precedence (priority) than “and“.

if statement with “or”:

PHP
<p>
  <?php 
  // example 1
  if ($a > $b || $a = $b) {
    echo "a is bigger or equal to b";
  }
  
  // example 2
  if ($a > $b or $a = $b) {
    echo "a is bigger or equal to b";
  }

  ?>
</p>

This will check if the value of “$a” is bigger than the one of “$b” or if “$a” is equal to the value of “$b” meaning that if either of those is true it will output “a is bigger or equal to b“.

Both examples will work the same though it is recommended that you use “||” since it has a greater precedence (priority) than “or“.

Switch statement

The switch statement is similar or almost identical even to if & elseif statement. The advantages of using a switch case is that it can be faster than an if & elseif statement because it jumps directly to the matching case instead of going through every line of code and it generally offers better readability.

example using a switch case compared to an if & elseif statement:

PHP
<?php
// This switch statement:

switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
}

// Is equivalent to:

if ($i == 0) {
    echo "i equals 0";
} elseif ($i == 1) {
    echo "i equals 1";
} elseif ($i == 2) {
    echo "i equals 2";
}
?>

Both examples result so if “$i” has a value of 1 both will output “i equals 1“, tough in comparison in the if & elseif statement it has to run 7 lines of code while in the switch case it only has to run 5 lines of code.

Amount of elseif / casesif & elseif line amountswitch line amount
155
275
395
10235

So as seen above the more elseif you have the better it is to use switch cases.

There is a special case for the switch statement and that is the default case. This case matches anything that didn’t match any other cases. For example:

PHP
<?php
switch ($i) {
    case 0:
        echo "i equals 0";
        break;
    case 1:
        echo "i equals 1";
        break;
    case 2:
        echo "i equals 2";
        break;
    default:
       echo "i is not equal to 0, 1 or 2";
}
?>

What’s special here it that if it doesn’t match any case it reverts to its default that’s given in this case “i is not equal to 0, 1 or 2“. Tough it still acts as a “case” meaning it will not be executed if there’s a matching case. Of course you can’t have multiple default’s otherwise you will get an error and it’s standard practise that you place the default case at the end.

Match expression

Match expressions are similar to switch statements but more concise and powerful. They evaluate a given expression and return a value based on matching cases. They provide an even better readability, and same as switch statements they use an identity check (===) meaning they not only check if the value is the same like a equality check (==) but they also check the datatype.

Here’s an example of how a match expression looks like:

PHP
<?php
// example 1
$food = 'cake';

$return_value = match ($food) {
    'apple' => 'This food is an apple',
    'bar' => 'This food is a bar',
    'cake' => 'This food is a cake',
};

var_dump($return_value); // Outputs: string(19) "This food is a cake"

// example 2
$food = 'cake';

$return_value = match ($food) {
    'apple' => 'This food is an apple',
    'bar' => 'This food is a bar',
    'cake' => 'This food is a cake',
};

echo $return_value; // Outputs: "This food is a cake"
?>

These examples are almost identical the only difference is which function i used to output the value stored in “$return_value“. With “echo” it will just give the simple string but with “var_dump” it gives the datatype and the amount of characters stored.

Then here’s an example with comparison operators:

PHP
<?php
$age = 18;

$output = match (true) {
    $age < 2 => "Baby",
    $age < 13 => "Child",
    $age < 18 => "Teenager",
    $age >= 18 => "Young adult",
    $age >= 28 => "Adult",
    $age >= 45 => "Old adult"
    default => "Age unknown"

};

var_dump($output); // Output: "Young adult"
?>

This gives an output depending on how big the given age is. Same as in the switch expression you can also give it a default value also displayed in the example above.

Arrays

There are a bunch of different types of arrays but for now lets look at the main 4:

  • One-Dimensional Arrays (1D Arrays)
  • Two-Dimensional Arrays (2D Arrays)
  • Dynamic Arrays
  • Associative Arrays

Here are all the different array functions that there are in php: Array Functions
And to show arrays especially with numbers you can’t use “echo” instead use “print_r()“.

One-Dimensional Arrays (1D Arrays)

Arrays start with an index of 0 not 1 so if you want to call the first number in an array you have to call the index 0.

These are the simplest type of arrays, consisting of a linear collection of elements stored in a single row. Each element is accessed using a single index. They are commonly used for storing sequential data like a list of numbers, strings, or objects. For example, a list of student scores or product prices is well-suited for a 1D array.

Example:

PHP
$array = [5, 10, 15, 20];

Here’s how you can add and remove a value to a one-dimensional array:

PHP
// Initialize an array
$array = [1, 2, 3, 4, 5];

// Add an element at the end
$array[] = 6;  // $array becomes [1, 2, 3, 4, 5, 6]

// Add a single or multiple elements
array_push($arr, 6, 7, 8); // $array becomes [1, 2, 3, 4, 5, 6, 7, 8]

// Remove the last element
array_pop($array);  // $array becomes [1, 2, 3, 4, 5] / [1, 2, 3, 4, 5, 6, 7]

// Merge 2 1D arrays 
$arr1 = [1, 2, 3];
$arr2 = [4, 5, 6];

$merged = array_merge($arr1, $arr2); // $arr1 and $arr2 become $merged [1, 2, 3, 4, 5, 6]

Two-Dimensional Arrays (2D Arrays)

A 2D array is an array of arrays, structured like a grid or table with rows and columns. Each element is accessed using two indices, one for the row and one for the column. They are commonly used for working with data that naturally fits into a tabular format, such as spreadsheets, matrices in mathematics, or pixel data in images. For instance, a chessboard can be represented as a 2D array.

Example:

PHP
$array = [
   [1, 2, 3],
   [4, 5, 6],
   [7, 8, 9]
];

Here’s how you can add and remove a value to a two-dimensional array:

PHP
// Initialize a 2D array
$array= [
    [1, 2, 3],
    [4, 5, 6],
    [7, 8, 9]
];

// Add a row at the end
$array[] = [10, 11, 12];  // $array becomes [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]

// Add a single or multiple rows
array_push($array, [10, 11, 12], [13, 14, 15]); // $array becomes [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12], [13, 14, 15]]

// Remove the last row
array_pop($array);  // $array becomes [[1, 2, 3], [4, 5, 6], [7, 8, 9]] / [[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]

// Merge 2 2D arrays
$matrix1 = [
    [1, 2],
    [3, 4]
];

$matrix2 = [
    [5, 6],
    [7, 8]
];

$merged = array_merge($matrix1, $matrix2); // $matrix1 and $matrix2 become $merged [[1, 2], [3, 4], [5, 6], [7, 8]]

Dynamic Arrays

Unlike static arrays with a fixed size, dynamic arrays can grow or shrink during runtime. This flexibility allows you to add or remove elements as needed without predefining the size of the array. In PHP, arrays are dynamic by default. You can append new elements to an array easily using the syntax $array[] = value;. Dynamic arrays are useful when the size of the dataset is unknown at the start or changes during the program’s execution, such as managing a list of user inputs or dynamically generated data.

Example:

PHP
$array = [1, 2, 3];

What “print_r” does while it also shows the index of each number inside the array its used to show the array since its full of integers (numbers).

Here’s how you can add and remove a value to a dynamic array:

PHP
// Initialize a dynamic array
$array= [1, 2, 3];

// Add an element
$array[] = 4;  // $array becomes [1, 2, 3, 4]

// Adding multiple elements during the run time
$dynamicArray = [];
for ($i = 1; $i <= 5; $i++) {
    array_push($dynamicArray, $i); // Appending elements  , $dynamicArray becomes [1, 2, 3, 4, 5]
}


// Remove the last element
array_pop($array);  // $array becomes [1, 2, 3]

// Merge 2 dynamic arrays
$dynamic1 = range(1, 5);
$dynamic2 = range(6, 10);

$merged = array_merge($dynamic1, $dynamic2); // $dynamic1 and $dynamic2 become $merged [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Associative Arrays

Associative arrays use key-value pairs instead of numerical indexes, allowing you to map unique keys to specific values, meaning instead of (0, 1, 2, etc.) being the indexes it will be each key (name, author, releaseYear, etc.) In PHP, associative arrays are implemented using the standard array type. Keys can be strings or integers, making them ideal for storing structured data such as configurations, mappings, or user information.
Associative arrays are commonly used to organize data for fast lookups, like mapping product IDs to details, or storing user profiles where fields like "name" or "email" correspond to specific values.

Example:

PHP
$books = [
    [
        "name" => "Metro 2033",
        "author" => "Dmitry Glukhovsky",
        "releaseYear" => 2002,
        "bookLink" => "https://www.google.com/search?sca_esv=2519e3bcac7d97bc&biw=1920&bih=945&q=Metro+2033+(novel)"
    ],
    [
        "name" => "Metro 2034",
        "author" => "Dmitry Glukhovsky",
        "releaseYear" => 2009,
        "bookLink" => "https://www.google.com/search?sca_esv=2519e3bcac7d97bc&biw=1920&bih=945&q=Metro+2034"
    ],
    [
        "name" => "Metro 2035",
        "author" => "Dmitry Glukhovsky",
        "releaseYear" => 2015,
        "bookLink" => "https://www.google.com/search?sca_esv=2519e3bcac7d97bc&biw=1920&bih=945&q=Metro+2035"
    ],
    [
        "name" => "The Lord of the Rings",
        "author" => "John Ronald Reuel Tolkien",
        "releaseYear" => 1954,
        "bookLink" => "https://www.google.com/search?q=lord+of+the+rings+novel"
    ]
];

$filteredBooks = array_filter($books, function ($book) {
    return $book["releaseYear"] >= 1950 && $book["releaseYear"] <= 2005;
});

The highlighted function filters all the books in the array and picks the ones released in 1950 or later and in 2005 or earlier.
The “array_filter” is a built in function by php that you can call if you want to sort items in an array like in this example.

If you call this function like this:

PHP
<ul>
    <?php foreach ($filteredBooks as $book) : ?>
        <li>
            <a href="<?= $book["bookLink"] ?>" target="_blank">
                <?= $book["name"]; ?> (<?= $book["releaseYear"] ?>) - By <?= $book["author"] ?>
            </a>
        </li>
    <?php endforeach; ?>
</ul>

If your wondering what the foreach does you can learn about it here: foreach explanation

This code uses a foreach loop to go through each book in the $filteredBooks array. Each book is an associative array containing details like the name, release year, author, and a link. The loop takes these details and displays them as clickable links in an unordered list (<ul>). Each list item (<li>) shows the book’s name, release year, and author, with the name being a hyperlink to the book’s link.

You will get following output (design might be different but the content should be the same):

Here’s how you can add and remove a value to a dynamic array:

PHP
// Initialize an associative array
$array= [
    "name" => "John",
    "age" => 30
];

// Add a new key-value pair
$array["address"] = "123 Main St";  // $array becomes ["name" => "John", "age" => 30, "address" => "123 Main St"]

// Add a single or multiple key-value pairs
$assocArray = array_replace($assocArray, ["city" => "New York", "country" => "USA"]); // $array becomes ["name" => "John", "age" => 30, "address" => "123 Main ST", "city" => "New York"]

// Remove a key-value pair
unset($array["age"]);  // $array becomes ["name" => "John", "address" => "123 Main St"] / ["name" => "John", "address" => "123 Main St", "city" => "New York"]

// Merge 2 associative arrays
$assoc1 = ["name" => "Alice", "age" => 25];
$assoc2 = ["city" => "London", "country" => "UK"];

$merged = array_merge($assoc1, $assoc2); // $assoc1 and $assoc2 become $merged ["name" => "Alice", "age" => 25, "city" => "London", "country" => "UK"]

Be careful when merging 2 associative arrays because if they have the same key it will keep the value for that key from the latter, meaning from the one that is mentioned the last in the code. In the case above it would be “$assoc2“. Here’s what i mean:

PHP
$assoc1 = ["name" => "Alice", "age" => 25];
$assoc2 = ["name" => "Bob", "city" => "London"];

// merge example 1
$merged = array_merge($assoc1, $assoc2); // "name" will be "Bob"
print_r($merged);

// merge example 2
$merged = $assoc1 + $assoc2; // Keeps "Alice" as the name
print_r($merged);

“foreach”

The foreach construct provides a simple way to pass / cycle through arrays. “foreach” only works with arrays and objects and will return an error if you try to apply it to a variable with a different data type or an uninitialized variable.

In the following example the foreach will go through the book in the “book” array that matches the “filteredBooks” function it will “echo” out the name, the release year and the author:

PHP
<ul>
    <?php foreach ($filteredBooks as $book) : ?>
        <li>
            <a href="<?= $book["bookLink"] ?>" target="_blank">
                <?= $book["name"]; ?> (<?= $book["releaseYear"] ?>) - By <?= $book["author"] ?>
            </a>
        </li>
    <?php endforeach; ?>
</ul>

So basically foreach is literally for each item in this array ($book) that matches the conditions of this function ($filteredBooks) echo: $book[“name”]; ?> () – By <?= $book[“author”].

functions

In PHP, a function is a block of reusable code that performs a specific task. Functions can accept arguments (input values), process them, and optionally return a result. They help make code modular, more readable, and easier to maintain. Meaning you can but a task that you will use multiple times in a function instead of writing the whole code each time you can just call the function for example debugging you will use the dump & die a lot to give you a certain output (dump) and the “kill” off the rest of the code so that it stops after that line with the “die();” function (built in with PHP). Lets get that in a visual perspective:

Instead of writing this every single time when debugging every few lines:

PHP
    echo "<pre>";
    var_dump($value);
    echo "</pre>";

    die();

You can just put the whole code in a function and then you will only have to call the function:

PHP
function dd($value) {
    echo "<pre>";
    var_dump($value);
    echo "</pre>";

    die();
}

The name of the function us usually dd for dump & die. So now every time you want to “dump & die” instead of having to write the code above you can just write / call: “dd();“. The “echo <pre> & echo </pre>” are just there so it will be more readable.

Tags: