PHP is a programming language for building web pages. PHP code runs on the server, then the result is sent to the browser as plain HTML. This tutorial covers the basics: installation, variables, branching, loops, functions, and printing HTML.

Installing PHP

On Arch Linux, install PHP with pacman. The command is one line:

sudo pacman -S php

Check the installed version with this command:

php -v

The result should look like PHP 8.3.6 (the numbers may differ). If you see a “command not found” error, PHP is not installed yet.

Hello world via CLI

CLI means the command line (command line interface). Create a file called halo.php with this code:

<?php
echo "Halo, dunia!\n";

Run it from the terminal with this command:

php halo.php

The result: Halo, dunia! is printed in the terminal.

Note: PHP code must start with the <?php tag. Without that tag, PHP treats the file contents as plain text and does not run the code. The closing tag ?> can be left out at the end of a file, and that is actually recommended for files that contain only PHP.

One more note: a PHP file must be run through PHP, as in the command above. Do not open a .php file directly from the file manager by double-clicking it. A browser cannot run PHP, so the code will not run and will only show up as text.

Flow of a .php file processed by PHP into HTML

Variables

A variable is a labeled box for storing a value. In PHP, a variable name always starts with a dollar sign ($). Write the name, then an = sign, then the value. End each command line with a semicolon (;).

<?php
$nama = "Briyan";
$umur = 25;

A variable name can contain letters, numbers, and underscores. It cannot start with a number, and it cannot contain spaces. Variable names are case-sensitive: $nama and $Nama are two different variables.

Dollar variables as labeled boxes holding values

Note: forgetting the dollar sign makes PHP treat the name as a constant, not a variable. Forgetting the semicolon makes PHP throw an error and stop the program. These two mistakes are the most common ones when starting out with PHP.

Basic data types

Every value has a type (a kind of data). The four basic types used most often are:

  • string: text, written between quotes. Example: “Briyan”.
  • int (integer): a whole number. Example: 25.
  • float: a decimal number, using a dot instead of a comma. Example: 19.5.
  • bool (boolean): only true or false. All letters are lowercase.
<?php
$nama = "Briyan";   // string
$umur = 25;         // int
$harga = 19.5;      // float
$lulus = true;      // bool

There is also array, a collection of values inside square brackets. Example: [“apel”, “mangga”, “jeruk”]. Take one item out with its position number (index), starting from 0. $buah[0] is “apel”.

Join text and variables with a dot (.), not a plus sign. Example: echo “Halo, “ . $nama . “!”;.

if / else

if runs code only when its condition is true. else runs other code when the condition is false. This is called branching.

<?php
$umur = 20;

if ($umur >= 18) {
    echo "Boleh masuk";
} else {
    echo "Belum boleh";
}

Comparison operators used most often: == (equal to), != (not equal to), > (greater than), < (less than), >= and <=.

Note: to compare, use == (two equals signs). One equals sign (=) means assigning a value, not comparing. Using the wrong one makes the condition always true.

Flow of if / else (branching)

for loop

A loop repeats code without writing it many times. for is used when the number of repeats is already known. This example prints the numbers 1 to 5:

<?php
for ($i = 1; $i <= 5; $i++) {
    echo "Hitungan ke-" . $i . "\n";
}

The result:

Hitungan ke-1
Hitungan ke-2
Hitungan ke-3
Hitungan ke-4
Hitungan ke-5

The part $i++ means add 1 to $i each round. Without that increment, the loop runs forever and the program hangs. Press Ctrl+C in the terminal to stop it.

foreach loop

foreach goes through the items of an array, one by one. It fits lists such as hobbies or fruit names.

<?php
$buah = ["apel", "mangga", "jeruk"];

foreach ($buah as $item) {
    echo $item . "\n";
}

The result:

apel
mangga
jeruk

The variable $item changes its content each round: first “apel”, then “mangga”, then “jeruk”.

Functions

A function is a named block of code that can be called many times. Write it once, use it anywhere. A function is made with the function keyword, then a name and parentheses. A function can take input (parameters) and give back a result (return).

<?php
function sapa($nama) {
    return "Halo, " . $nama . "!";
}

echo sapa("Briyan");  // Halo, Briyan!
echo "\n";
echo sapa("Kirana");  // Halo, Kirana!

Call a function by writing its name followed by parentheses. Put the value to send inside the parentheses. Forgetting the parentheses means the function is not run, only named.

echo HTML

PHP can print HTML tags with echo. This is how PHP builds web pages: PHP works on the data, then prints the HTML that is sent to the browser.

<?php
$nama = "Briyan";

echo "<h1>Halo, " . $nama . "</h1>\n";
echo "<p>Selamat datang di halaman saya.</p>\n";

The result is plain HTML, like this:

<h1>Halo, Briyan</h1>
<p>Selamat datang di halaman saya.</p>

Note: quotes inside a string must be a different kind from the opening quote. If a string opens with a double quote (“), use single quotes (’) for HTML attributes inside it, or the other way round. If they are the same, PHP thinks the string ended halfway through.

Common mistakes

  • Forgetting the semicolon at the end of a command line.
  • Forgetting the dollar sign in front of a variable name.
  • Forgetting the <?php tag at the start of the file.
  • Comparing with = when it should be ==.
  • Opening a .php file directly in the browser instead of running it through PHP.
  • Forgetting to close the quotes on a string.
  • Adding the result of readline() without (float), so the text sticks together.
  • Dividing by zero, which makes PHP give a warning.

If you get stuck, ask Muse (yue) to explain the line that errors. Paste the error message from the terminal so the explanation is exact.

Full program: bio page

This program prints a bio page as HTML. The data is kept in variables, then printed with echo. The hobby list is printed with foreach.

Copy the code below into a file called biodata.php, then run it with php biodata.php.

<?php
$nama = "Briyan Febri";
$umur = 25;
$kota = "Jakarta";
$hobi = ["membaca", "lari", "ngoding"];

echo "<!DOCTYPE html>\n";
echo "<html>\n<head><title>Biodata</title></head>\n<body>\n";
echo "<h1>Biodata</h1>\n";
echo "<p>Nama: " . $nama . "</p>\n";
echo "<p>Umur: " . $umur . " tahun</p>\n";
echo "<p>Kota: " . $kota . "</p>\n";
echo "<h2>Hobi</h2>\n";
echo "<ul>\n";
foreach ($hobi as $item) {
    echo "<li>" . $item . "</li>\n";
}
echo "</ul>\n";
echo "</body>\n</html>\n";

The result:

<!DOCTYPE html>
<html>
<head><title>Biodata</title></head>
<body>
<h1>Biodata</h1>
<p>Nama: Briyan Febri</p>
<p>Umur: 25 tahun</p>
<p>Kota: Jakarta</p>
<h2>Hobi</h2>
<ul>
<li>membaca</li>
<li>lari</li>
<li>ngoding</li>
</ul>
</body>
</html>

How it works: variables hold the bio data. echo prints the HTML tags one by one. foreach prints each hobby as one list item (<li>). The final result is valid HTML that can be opened in a browser.

Full program: mini calculator

This program asks for two numbers, then shows the results of adding, subtracting, multiplying, and dividing them. readline() reads one line typed by the user. (float) turns the typed text into a decimal number so it can be calculated with.

Copy the code below into a file called kalkulator.php, then run it with php kalkulator.php.

<?php
$a = (float) readline("Angka pertama: ");
$b = (float) readline("Angka kedua: ");

echo "Tambah: " . ($a + $b) . "\n";
echo "Kurang: " . ($a - $b) . "\n";
echo "Kali: " . ($a * $b) . "\n";
echo "Bagi: " . ($a / $b) . "\n";

A sample run, with the numbers 10 and 4:

Angka pertama: 10
Angka kedua: 4
Tambah: 14
Kurang: 6
Kali: 40
Bagi: 2.5

How it works: readline() reads the numbers from the user. (float) turns the text into numbers, because without it “10” + “4” can be calculated wrong. The operators +, -, *, and / compute the four operations. Division gives a decimal, so 10 / 4 is 2.5. Do not enter 0 as the second number, because dividing by zero gives a warning.