Introduction to PHP
Every language starts with the same basics: variables, types, loops, and conditions. Here is how PHP does them.
Basic PHP syntax
A PHP file should start with the opening tag <?php, and you can end it with the closing tag ?>. If the file contains only PHP, it's recommended to leave out the closing tag.
Every instruction in PHP must end with a semicolon ;
<code class="language-php"><?php
echo 'Hello world';
</code>Comments
Comments are lines in the code that are not executed as part of your application. They are only there to help other developers understand the code.
PHP supports C, C++, and Unix style comments.
Example:
<code class="language-php">// This is a single line comment
# This is also a single line comment
/**
This is
a multiline comment
*/
echo /** inline comment */ "hi";
// The line above prints "hi" and ignores the comment
</code>Usually, your code should be expressive and should not need comments. Use comments to explain why you wrote the code that way, not what it is doing. Unless your code is a mess and you can't fix it now, then it's better to add a comment explaining what is happening.
echo
echo is a PHP language construct. It outputs one or more strings. It doesn't return anything, so you can't use it inside an expression.
Example of echo:
<code class="language-php"><?php
echo 'string1', 'string2';
// or
echo "Here's one string";
</code>print
print is another language construct. It does the same job as echo, but it can only print one string at a time, and it always returns 1.
Example of print:
<code class="language-php"><?php
print 'String';
// or
print('String');
</code>PHP variables
A variable is a name that stands for a value, and the value can change later. In PHP, a variable starts with $ followed by a name. For example: $name = 'Oliver Queen';. Here $name is the variable and Oliver Queen is its value.
Some rules for PHP variables
- A variable starts with the
$sign. - Variables are case sensitive, so
$xis not the same as$X. - After the
$, a valid name starts with a letter or an underscore, followed by any letters, numbers, or underscores. $thisis a special variable and you can't assign to it.
By default, PHP assigns variables by value. That means the value is copied into the new variable. You can also assign by reference with &. Then nothing is copied, and the new variable becomes an alias of the old one.
Example of assigning by value:
<code class="language-php"><?php
$name = 'Oliver Queen';
$oliver = $name;
// $name and $oliver now have the same value: 'Oliver Queen'
// If I change $name to 'John Diggle',
// $oliver is not affected
$name = 'John Diggle';
echo $name, ' ', $oliver;
// Prints: John Diggle Oliver Queen
</code>Example of assigning by reference:
<code class="language-php"><?php
$name = 'Oliver Queen';
$oliver = &$name;
// $oliver is now an alias for $name
// If I change one of them, the other changes too
$name = 'John Diggle';
echo $name, ' ', $oliver;
// Prints: John Diggle John Diggle
</code>PHP constants
Like a variable, a constant is a name that stands for a value. The difference is that you can't change a constant after it's defined. So we use constants for data that should never change.
The naming rules are the same as for variables, but a constant doesn't start with $.
Example:
<code class="language-php"><?php
const NAME = 'Oliver Queen';
// NAME can't be changed at runtime.
// Trying to change it leads to an error.
</code>Another way to define a constant is the define function. But you can't use define inside a class definition. It always has to be outside of any class.
const can be used both inside and outside a class definition.
define example:
<code class="language-php"><?php
// The first argument is the name of the constant, the second one is the value.
define('A_NAME', 'Oliver Queen');
// To check if a constant is already defined, use the `defined` function.
// It returns true if the constant exists and false if not.
print defined('A_NAME'); // Prints 1
</code>You can define a constant with lower case letters, but the convention in PHP is to use upper case.
Before PHP 8, define could create case insensitive constants. This was deprecated in PHP 7.3 and removed in PHP 8.
const vs define
Both define and const create constants, but there are some differences. From the most to the least important:
constdefines the constant at compile time, whiledefinedefines it at runtime.definecan't be used inside a class definition, whileconstcan.definecan be used inside a control structure (like anif), whileconstcan't.
PHP data types
Variables hold data, and in PHP every piece of data has a type. 'Oliver Queen' is a string, and 1 is an integer. PHP usually decides the type of a variable at runtime, based on the data stored in it.
Types
PHP supports ten primitive types, grouped like this:
Scalar types
bool
A bool is either true or false.
<code class="language-php"><?php
$isRunning = true;
$isRunning = false;
</code>Control structures like conditions and loops work with booleans. In PHP, any value can be converted to a boolean, either by you or automatically by the control structure.
<code class="language-php"><?php
$x = (bool)0; // false
$x = (bool)-0; // false
$x = (bool)0.0; // false
$x = (bool)-0.0; // false
$x = (bool)''; // false
$x = (bool)'0'; // false
$x = (bool)null; // false
$x = (bool)[]; // false
$y = (bool)1; // true
$y = (bool)1.1; // true
$y = (bool)'Any non empty string'; // true
$y = (bool)'false'; // true, because it is a non empty string
$y = (bool)[1, 2, 3]; // true, because it is a non empty array
</code>int
An int is any whole number, like 1, 2, or -3. You can find the smallest and biggest possible integers with the predefined constants PHP_INT_MIN and PHP_INT_MAX.
In PHP, you can write integers in multiple ways:
<code class="language-php"><?php
$age = 33; // decimal 33
$age = 0x21; // 33 in hex, prefixed with 0x
$age = 041; // 33 in octal, prefixed with 0
$age = 0b100001; // 33 in binary, prefixed with 0b
</code>For readability, you can separate digits with underscores. So instead of 1000000000 you can write $price = 1_000_000_000; and PHP reads it as 1000000000.
float
A float is any real number, like 1.0, 2.2, or -2.88. Like with int, PHP_FLOAT_MIN and PHP_FLOAT_MAX give you the limits.
Example of how PHP picks the types:
<code class="language-php"><?php
$isGood = true; // bool
$name = 'Oliver Queen'; // string
$age = 33; // int
$price = 99.99; // float
</code>string
A string is any text, like 'Any text'. In PHP, a string is wrapped in single or double quotes, like $name = 'Oliver'; or $name = \"Oliver\";. The difference is that inside double quotes you can use variables:
<code class="language-php"><?php
$name = 'Oliver';
$fullName = "{$name} Queen";
echo $fullName; // Prints Oliver Queen
$fullName = '{$name} Queen';
echo $fullName; // Prints {$name} Queen
</code>Heredoc and Nowdoc
Heredoc and Nowdoc are another way to write strings, usually for multiline text. The syntax is <<< plus an identifier of your choice. For example, if you are writing an SQL query you can use SQL, so your string starts with <<<SQL and ends with SQL;. If you are printing HTML, you might use <<<HTML and end with HTML;.
Heredoc
<code class="language-php"><?php
$isBestFriend = 1;
// You can use variables inside, like in double quoted strings
$query = <<<SQL
SELECT * FROM friends WHERE is_best = $isBestFriend;
SQL;
</code>Nowdoc: the same, but the identifier is wrapped in single quotes.
<code class="language-php"><?php
// You can't use variables inside a Nowdoc
$query = <<<'SQL'
SELECT * FROM friends WHERE is_best = 1;
SQL;
</code>String concatenation
You can join two strings with the . operator.
Example:
<code class="language-php"><?php
$firstName = 'Oliver';
$lastName = 'Queen';
$fullName = $firstName . ' ' . $lastName;
echo $fullName; // Prints: Oliver Queen
echo "{$firstName} {$lastName}"; // Prints: Oliver Queen
</code>Compound types
array
An array is a list of values of any type: numbers, strings, null, resources, other arrays, anything.
Simple array example:
<code class="language-php">$names = array('Oliver', 'John', 'Thea');
</code>The short syntax for array() is square brackets []. So array(1, 2, 3) is the same as [1, 2, 3]. In the rest of this article, we only use square brackets.
In PHP, there are two kinds of arrays: indexed and associative.
Indexed arrays: the keys are numbers, starting from zero.
Associative arrays: the keys are names you choose.
Example:
<code class="language-php">$indexedArray = [
'A', 'B', 'C', 'D'
];
$associativeArray = [
'color' => 'Red',
'price' => 2000
];
</code>You can use a PHP array as a list, a map, a collection, a queue, a stack, and more.
Array access
Indexed array access
To get an element of an indexed array, you use its index. If we have $array = ['A', 'B', 'C']; and you want B, you need its index, which is 1, because the first index is zero. So $array[1] is B.
<code class="language-php">$array = ['A', 'B', 'C'];
$array[0]; // A
$array[1]; // B
$array[2]; // C
</code>Associative array access
Same idea, but you use the key, and the key is usually a string. With $map = ['color' => 'Red', 'price' => 2000], to get Red you use its key color. So $map['color'] is Red.
<code class="language-php">$map = ['color' => 'Red', 'price' => 2000];
$map['color']; // Red
$map['price']; // 2000
</code>Changing arrays
Changing an array means adding, changing, or deleting elements. In PHP, you use the same square bracket syntax [] for both kinds of arrays.
<code class="language-php">$array = ['A', 'B', 'C'];
// Replace the first element with a small a
$array[0] = 'a'; // The array is now ['a', 'B', 'C']
</code><code class="language-php">$map = ['color' => 'Red', 'price' => 2000];
// Change the color to 'Green'
$map['color'] = 'Green'; // The array is now ['color' => 'Green', 'price' => 2000]
</code>Adding an element to an indexed array
<code class="language-php">$array = ['A', 'B', 'C'];
// Add D to the end of the array
$array[] = 'D'; // The array is now ['A', 'B', 'C', 'D']
</code>Adding an element to an associative array
For an associative array, you decide the key. If we have $map = ['color' => 'Red'] and you want to add a price, the key is price, so you write $map['price'] = 2000.
Deleting an element
To delete an element from either kind of array, use unset. It destroys the variable you pass to it, and for arrays it removes the element.
Example:
<code class="language-php">$array = ['A', 'B', 'C'];
// Delete B
unset($array[1]); // The array is now [0 => 'A', 2 => 'C']
// Note: unset does not re index the array.
// Use array_values($array) if you need [0 => 'A', 1 => 'C'].
</code>object
Like an array, an object can hold multiple values of different types.
- It is an instance of a class, either built in or defined by you.
stdClassis a generic empty class you can use to create simple objects.
A basic PHP class looks like this:
<code class="language-php">class MyClass {
}
</code>Then you create objects of your class with the new keyword:
<code class="language-php">$object1 = new MyClass();
</code>callable
As the name says, a callable is something you can call, like a function, a closure, or an invokable class.
iterable
iterable is a pseudo type. It accepts any array, or any object that implements Traversable, so you can loop over it with foreach.
Example:
<code class="language-php"><?php
$hobbies = ['Reading', 'Video games']; // array of strings
$things = ['A', 1, true, false, ['anything']]; // array of mixed types
$something = new stdClass(); // object
$callable = function () { echo "HI :)"; }; // callable
</code>Special types
resource
A reference to an external resource, like a file, a database connection, or a stream.
NULL
A variable with no value.
Example:
<code class="language-php"><?php
$nothing = NULL; // NULL
$resource = fopen('afile.txt', 'r'); // resource
</code>You can get the type of any variable with the gettype function. If $x = 1, then gettype($x) returns integer.
More info in the gettype documentation.
Type casting
In PHP, you can force a value to be of a specific type. You do it by writing the type in parentheses in front of the value, like (type)$var.
Example:
<code class="language-php"><?php
$age = '22'; // '22' is a string
echo gettype($age); // Prints string
$age = (int)'22';
echo gettype($age); // Now it prints integer
</code>Control structures
Control structures let you control how your code runs. In other words, they let your code behave differently depending on the input.
Loops
Loops repeat a statement or a block of code. For example, you can print a string 100 times.
PHP has four kinds of loops: while, do while, for, and foreach. Each one has its own use.
while
while is very simple. It takes one boolean expression, the loop condition. As the name says: while the condition is true, it keeps running the code in its body.
Example of a PHP while loop:
<code class="language-php"><?php
while (true) {
echo "I love PHP";
}
</code>This is a simple infinite loop. It keeps printing I love PHP until we stop it manually, because the condition is always true.
Animation of how the while loop works
do while
do while works exactly like while, with one difference: it checks the condition at the end of each iteration instead of at the beginning.
So even if the condition is false, the body runs at least once.
Example:
<code class="language-php"><?php
do {
echo "I love PHP";
} while ($someCondition);
</code>for
The for loop is not as simple as while, and its syntax is different. It takes 3 expressions. The first is the initial expression, which runs only once at the start. The second is the condition, which is checked before every iteration. The third is the update expression, which runs at the end of every iteration.
Animation of how the for loop works
A simple for loop:
<code class="language-php"><?php
for ($counter = 0; $counter < 100; $counter++) {
echo $counter;
}
</code>- First it initializes
$counter = 0. - Then it checks the condition.
$counteris less than 100, because it is0for now. - Then it runs the body, which prints
0. - Then it runs the update expression
$counter++, which increments$counterby1. Now it's1. - Then it checks the condition again, and
1is still less than100. - While the condition is true, it goes back to step 3. Otherwise it exits the loop.
foreach
foreach is a special loop used mainly to iterate over arrays and objects. It gives you access to the current element.
There is no condition with foreach. It keeps going until it reaches the last element.
Basic foreach example:
<code class="language-php"><?php
$array = ['A', 'B', 'C'];
foreach ($array as $arrayElement) {
echo $arrayElement;
}
</code>Another example, using the key too:
<code class="language-php"><?php
$car = [
'color' => 'Red',
'made_in' => 'Germany',
'brand' => 'Mercedes Benz',
];
foreach ($car as $key => $value) {
echo "$key is $value\n"; // \n just prints a new line
}
// The result:
/**
color is Red
made_in is Germany
brand is Mercedes Benz
*/
</code>foreach can also iterate over the public properties of an object.
A very important note: the variable created by foreach stays alive after the loop. In the last example, $value still exists after the loop and holds the last value. Even worse, if you had a variable with the same name before the loop, foreach overwrites it.
This can lead to unexpected behavior and bugs.
Example:
<code class="language-php"><?php
$value = 'ABC';
$array = [1, 2, 3];
foreach ($array as $value) {
echo $value;
}
echo $value;
// This doesn't print 'ABC'. It prints 3,
// because 3 is the last value the foreach iterated over.
</code>So it's a good habit to unset the loop variable after the loop. This is especially important when you loop by reference (foreach ($array as &$value)).
<code class="language-php"><?php
foreach ($array as $value) {
echo $value;
}
unset($value);
</code>goto 🤦
goto is also a control structure. It jumps between sections of a PHP script. And it's the easiest way to create spaghetti code :) because it's so easy to abuse.
Example:
<code class="language-php"><?php
echo "1";
goto last;
echo "2";
echo "3";
last:
echo "4";
</code>The code above prints: 14
goto is considered bad practice and should be avoided. Some developers say it's useful to break out of deeply nested loops, but in my opinion, if we allow it once, we lose control, and later we will find it everywhere in our code.
Let's forget about it :D
Conditionals
Conditionals run a piece of code only when some condition is true. PHP has if, else, elseif, switch, and match.
if
if is one of the most important features in programming. It lets the software make a decision based on a condition.
<code class="language-php"><?php
if ($someExpression) {
echo "I love PHP";
}
</code>The code above prints I love PHP only if $someExpression is true.
Animation of a basic if statement:
else and elseif
else runs when the if condition is false, and elseif lets you check another condition.
<code class="language-php"><?php
if ($age < 18) {
echo "Too young";
} elseif ($age < 65) {
echo "Welcome";
} else {
echo "Welcome, enjoy the discount";
}
</code>match
match (since PHP 8) compares a value against a list of options and returns a result. Unlike switch, it uses strict comparison and doesn't need break.
<code class="language-php"><?php
$label = match ($statusCode) {
200 => 'OK',
404 => 'Not Found',
500 => 'Server Error',
default => 'Unknown',
};
</code>
If this was useful
Telc German B1 Exam Success Kit (20/80 Rule)
The 20% of German that keeps showing up in the telc B1 exam. Learn it first and walk in already knowing what to expect. €25