How to Start Developing in PHP

In the previous article you learned what PHP is and what it’s used for. In this article, we’ll focus on how to get PHP up and running and how to start developing. In simple demonstrations, we’ll show the basic constructions of the language and we’ll also talk about libraries and third-party frameworks.

First steps

We need to have PHP installed before we can start writing PHP scripts. Fortunately, PHP is available for every commonly used operating system and web server. On Ubuntu OS we can install PHP using the command sudo apt install php. To verify that the installation was successful, we can run the php -v command, which should have an output similar to this:

PHP 8.1.8 (cli) (built: Jul 11 2022 08:29:57) (NTS)
Copyright (c) The PHP Group
Zend Engine v4.1.8, Copyright (c) Zend Technologies
 with Zend OPcache v8.1.8, Copyright (c), by Zend Technologies

A better way to develop in PHP is to use docker containers. In this way, we’ll be able to work on different projects with different versions of PHP. You can find a sample project using docker, for example, here.

PHP language basics

If we have PHP installed, we can start programming ? Each PHP script is “delimited” by a tag:

<?php
// PHP kód
?>

We’ll start with the classic example of “Hello world!”. We create a “hello.php” file with the following content:

<?php
echo 'Hello world!';
?>

We simply run the script with the command “php hello.php”. The output is as follows:

PHP Hello world

But in order not to leave you with such a simple example, we’ll show the basic features and constructions of the PHP language. Keywords in PHP are not “case sensitive”, but it’s good to follow certain standards for clarity. Each PHP framework may have different standards for how to write code, but the basics are the same. 

PHP variables start with $, can only contain alphanumeric characters, and are created the first time they are assigned a value. PHP has weak dynamic typing, which means that the variable type is automatically assigned without declaration. In version 7, however, declarations have been added, and thus we have the possibility to determine the type of the variable. We distinguish local and global scope of variables:

  • Global scope: the variable is defined “everywhere”
  • Local scope: the variable is defined only in the current block (e.g. function body)

If we want to use a global variable in a local scope, we need to determine this using the keyword “global” at the beginning of the body of the function:

<?php
$a = 5;

function test($b, $c = 10) {
  global $a;
  static $d = 1;
  $result = $a + $b + $c + $d;
  $d++;
  return $result;
}

echo test(3);; // výstup 19
echo test(5, 5);; // výstup 17
?>

However, sometimes we don’t want the local variable to be deleted. For this purpose, we can use the static keyword when declaring a variable, which ensures that we can work with the current value of a given variable in subsequent function calls too. In the example above, you can see that in the first call of the test function the variable $d is initialized with the value 1, but at the next call it has the value 2.

In the previous example, you can also see how to declare and call a function. As you may have noticed, we only used one parameter in the first function call and two in the second one. In PHP, it’s possible to assign a default value to function arguments (in the example, the default value of 10 is assigned to the $c argument, which is applied if we don’t specify the value of the given argument when calling the function).

Basic PHP elements

Next, we’ll look at other basic elements of PHP that are essential for working with it.

PHP data types

Like any programming language, PHP has its built-in data types that are as follows:

  • string: character string
  • int: integer value
  • float or double: a real number of single and double precision
  • bool: logical data type (true/false)
  • array: field
  • null: indicates an empty value – if we declare a variable without the initial value, it will automatically have a null value

Operators in PHP

The operators in PHP are mostly the same as in other programming languages. More detailed explanations for each operator can be found here. In PHP we have the following operators:

  • Arithmetic: +, -, *, /, % (modulus), ** (exponent)
  • Assignment: =, +=, -=, *=, /=, %=
  • Comparison: ==, ===, !=, <>, !==, >, <, >=, <=, ⇔
  • Increment, decrement: $x++, ++$x, $x– , –$x
  • Logical: &&, ||, !
  • Concatenation of strings: ., .=

Conditions (if…else…, switch)

If we want to execute a part of a code based on some condition, we can use the construct if…else… , which has the following syntax:

if (podmienka) {
  kód sa vykoná ak podmienka je vyhodnotená ako pravdivá (true)
} else {
  kód sa vykoná ak podmienka nie je pravdivá (false)

When assigning a variable value based on a condition, we can also use the so-called ternary operator (?:):

$x = podmienka ? hodnota pre pravdivú podmienku : hodnota pre nepravdivú podmienku

If you want to execute a code according to the value of the variable and there are more options, it’s better to use the “switch” construct, which will execute the desired part of the code based on the value of the variable:

switch (n) {
  case hodnota1:
    Kód sa vykoná ak n=hodnota1;
    break;
  case hodnota2:
    Kód sa vykoná ak n=hodnota2;
    break;
  case hodnota3:
    Kód sa vykoná ak n=hodnota3;
    break;
    ...
  default:
    Kód sa vykoná ak n má inú hodnotu ako všetky vyššie vymenované hodnoty;
}

Cycles in PHP

In PHP, we have several types of cycles, which we’ll also show:

While

Executes a cycle body while the condition is true:

while (podmienka) {
  kód ktorý sa má vykonať
} 

$i = 10;
while ($i > 0) {
 echo $i . PHP_EOL;
 $i--;
}

Do while

Executes the cycle body once and then continues to execute it while the condition is true:

do {
  kód ktorý sa má vykonať
} while (podmienka); 

$str = '';
do {
 $str .= 'a';
 echo $str . PHP_EOL;
} while ($str !== 'aaaa');

For cycle

The body of a cycle is executed a certain number of times – we have to define the variable that will be incremented, the condition for the end of the cycle and the method of incrementing the “counter”:

for (inicializácia počítadla; podmienka; inkrementácia počítadla) {
  kód ktorý sa má vykonať
} 

for ($i = 0; $i < 5; $i += 2) {
 echo $i . PHP_EOL;
}

Foreach cycle

Executes the cycle body for each item in an array. There are two variants of the foreach cycle:

  • only the value of the item in the array is used in the first one
  • in the second one, in addition to the value, the key of the item in the array is also used
foreach ($pole as $hodnota) {
  kód ktorý sa má vykonať
} 

$array = [1 => 'one', 2 => 'two', 3 => 'three'];
foreach ($array as $val) {
 echo $val . PHP_EOL;
}
foreach ($pole as $kľúč => $hodnota) {
  kód ktorý sa má vykonať
} 

foreach ($array as $key => $val) {
 echo $key . ' => ' . $val . PHP_EOL;
}

In all types of cycles, we can use the commands “break” and “continue”:

  • break: to be used if we want to interrupt the execution of the entire cycle
  • continue: to be used if we want to skip the execution of the current cycle iteration

In addition to the above-mentioned basic functionalities/constructions that each programming language has in its own way, additional functionalities are also built into PHP, such as:

  • Working with databases
  • Parsing and working with XML
  • AJAX calls

PHP libraries

Even with a simple PHP script we can do basically everything, we can make our work easier by using libraries or software frameworks. They provide us with a platform over which we can create our applications and they save us a lot of time, as they have implemented all the commonly used functionalities.

The use of frameworks has a number of advantages:

  • It accelerates development
  • It reduces the amount of code we would have to write ourselves
  • Common functionalities are already implemented
  • It makes it easier to follow good coding practices
  • It’s safe
  • It provides easier code maintenance

Before we can start using any PHP framework, we need at least basic knowledge of PHP. It’s also good to know object-oriented PHP, as most frameworks are written in the OOP paradigm.

The most used PHP frameworks:

  • Laravel (web applications)
  • Zend Framework / Laminas Project
  • Symfony
  • Slim (micro framework for web applications and API)

In other articles in the series, we’ll give you a closer look at working with some of the frameworks.