Basics
PHP is a cross-platform deprecated scripting language. It allows developers to write code for web development projects of all sizes. PHP is still widely used in server-side web development, database management, and creating content management systems because it would be costly to replace all the architectures. It is an interpreted, high-level, and general-purpose language. PHP supports procedural, object-oriented, and functional programming paradigms. The extension of a PHP file is .php
.
To write in PHP, we need a server. We can host a local one on our computer using the XAMPP Control Panel. You can download it from here. After installation, start the Apache server. The PHP scripts have to be placed in the htdocs
folder inside the xampp
directory to be visible under the localhost/your_script_name.php
address in the web browser.
I do not recommend learning it unless you absolutely have to and definitely do not learn it as your first language. In this tutorial, I will assume you know all the basic programming concepts and only superficially describe the syntax (I will not explain these concepts). The more in-depth part of this tutorial will be about handling HTML forms and communication with a MySQL database.
Basic structure and methods
PHP code is written within the <body>
section of an HTML document (with a .php
extension) or in a separate .php
file, enclosed between the <?php
and ?>
tags. The echo
instruction is used to print values on the web page. Inside it, we can use HTML elements that will be rendered as part of the output, allowing us to mix PHP and HTML code seamlessly. This enables dynamic content generation within static HTML structures. In PHP, a semicolon is placed after each statement. We must indicate which instructions belong to, e.g., a loop, by putting them in braces (unless it's only one line).
In PHP, ==
checks if two values are equal, while ===
checks both the value and the type, meaning it returns true
only if both the value and the type are identical.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="PHP basics">
<title>PHP basics</title>
</head>
<body>
<?php
echo "<br><b>Hello World!</b><br>";
$x = 4;
echo $x;
// Quotation marks and apostrophes differ only when displaying variables (variables are parsed within quotation marks but not within apostrophes).
echo '<br>';
echo 'The value of $x', " is $x";
echo "<br>";
$z = "World!";
echo "Hello ", $z, "<br>";
// The operators in PHP are the same as those in C++.
$y = 3;
echo $x + $y, "<br>";
echo $x - $y, "<br>";
echo $x * $y, "<br>";
echo $x / $y, "<br>";
echo $x % $y, "<br>";
echo "$x + $y = " . ($x + $y); // dot is a concatenation operator
$a = 2;
$b = 1;
$b = $a++; // $a-- also exists
echo "<br> $b<br>";
$b = ++$a; // --$a also exists
echo "$b <br>";
$x = 2;
$x += 1; // -=, *=, /=, %= etc.
// Checking the type of a variable (the is_ methods return 1 for true and nothing for false)
$y = NULL;
echo is_array($y);
echo is_bool($y);
echo is_float($y);
echo is_integer($y);
echo is_null($y);
echo is_string($y);
echo "<br>" . gettype($y) . "<br>";
// Type casting
$a = "2";
$b = (int)$a;
// Long texts (text inside a heredoc is parsed, meaning variables within it are expanded, while nowdoc treats the content as a plain string without parsing variables)
$text = "<br>Text";
# heredoc
$lorem = <<<EOD
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin feugiat, lacus non aliquet sagittis, justo lectus mollis lorem, quis tempus augue velit a enim. Mauris finibus tellus odio. $text
EOD;
echo $lorem . "<br>";
# nowdoc
$lorem1 = <<<'EOD'
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin feugiat, lacus non aliquet sagittis, justo lectus mollis lorem, quis tempus augue velit a enim. Mauris finibus tellus odio. $text
EOD;
echo $lorem1;
// Defining constants
define("PI", 3.1415);
const NAME = 3.1415;
?>
</body>
</html>
Arrays
$array = array(2, 5, 7);
$array2 = [2, 5, 7];
echo "<br>" . $array[0];
$assoc_array = array("a" => "b", "c" => "d"); // an associative array = a map
echo "<br>" . $assoc_array["a"];
$assoc_array["c"] = "e";
echo "<br>" . $assoc_array["c"];
$assoc_array["f"] = "g";
echo "<br>" . $assoc_array["f"];
The functions with no parameters listed take only one - the array.
count() |
Returning the number of elements in an array (equivalent to sizeof() ). |
sort() , rsort() |
Sorting an array in ascending / descending order (uppercase letters are considered smaller than lowercase). |
asort() , arsort() |
Sorting an associative array in ascending / descending order based on the value. |
ksort() |
Sorting an associative array by key in ascending order. |
min() , max() |
Returning the minimum / maximum value of an array. |
array_pop() |
Returning the last element of an array and removing it. |
array_shift() |
Returning the first element of an array and removing it. |
array_reverse() |
Creating a copy of an array with reversed element order. |
array_sum() |
Returning the sum of the elements in an array. |
array_unique() |
Removing duplicates from an array. |
array_merge() |
Merging two arrays. |
shuffle() |
Shuffling the array's elements. |
print_r() |
Displaying the contents of an array. |
array_flip() |
Swapping the keys and values of an associative array. |
array_push($t, $v1, $v2, ...) |
Adding values $v1 , $v2 , ... at the end of array $t . |
range($s, $k, $c) |
Creating an array containing integers from $s to $k with step $c (optional). Example: range(1, 10, 2); (returns: [1, 3, 5, 7, 9] ). |
array_slice($t, $o, $m) |
Creating an array containing $m elements from array $t , starting from index $o . Example: array_slice([1, 2, 3, 4, 5, 6, 7, 8], 2, 3); (returns: [3, 4, 5] ). |
Loops
<style>
table, td {
border: 1px solid black;
border-spacing: 0;
}
</style>
// Multiplication table from a random range
$n = rand(10, 30); // generating a random number from 10 to 30
echo "<table>";
for ($i = 1; $i <= $n; $i++) {
echo "<tr>";
for ($j = 1; $j <= $n; $j++)
echo "<td>" . ($i * $j) . "</td>";
echo "</tr>";
}
echo "</table>";
$number = 132;
echo "The number $number written in reverse order is: ";
while ($number > 0) {
echo $number % 10;
$number = floor($number / 10);
}
$i = 1;
do {
echo "<br>X<br>";
} while ($i < 1);
$sum = 0;
$array = [7, 45, 23, 79, 90, 12, 34, 7, -4, 3];
foreach($array as $value) {
echo $value . "<br>";
$sum += $value;
}
echo "The sum of the array values is $sum.<br>";
$names = array('Peter' => 'Smith', 'Ada' => 'Jones', 'John' => 'Williams', 'Anne' => 'Brown');
foreach($names as $key => $value) {
echo $key . " " . $value . "<br>";
}
Conditional statements
$x = 126;
if ($x % 2 == 0) {
echo "Number $x is even<br>";
}
elseif ($x == 0) { // could be also: "else if" (with a space)
echo "Number $x is 0<br>";
}
else {
echo "Number $x is odd<br>";
}
$sign = "+";
$a = rand(0, 100);
$b = rand(0, 100);
echo "The generated numbers are $a and $b <br>";
switch($sign) {
case "+":
echo $a + $b;
break;
case "-":
echo $a - $b;
break;
case "*":
echo $a * $b;
break;
default:
echo "Operation not selected";
break;
}
$x = 10;
$condition = ($x > 10) ? 5 : 6;
Functions
- Local variables = inside functions
- Global variables = throughout the entire script except functions
- Superglobal variables = throughout the entire script
function func() {
echo "Function<br>";
}
func();
function addition($x, $y) {
return $x + $y;
}
echo addition(5, 3) . "<br>";
$x = 7;
function area() {
global $x; // accessing a global variable inside a function (could be also: $x = $GLOBALS['x'];)
$area = $x * $x;
echo "The area of a square with side $x is $area.<br>";
}
area();
function count1() {
static $a = 0; // a static variable
echo $a . "<br>";
$a++;
}
count1();
count1();
count1();
function increment(&$a) { // a reference
$a++;
}
$a = 5;
increment($a);
echo $a . "<br>";
function default_parameters($x = 1) {
echo $x;
}
default_parameters();
Strings
The functions with no parameters listed take only one - the string.
mb_strlen() |
Returning the number of characters in a string (its length). |
strtolower() , strtoupper() |
Converting a string to lowercase / uppercase. |
strrev() |
Reversing a string. |
trim() |
Removing whitespace characters from both ends of a string. |
ucwords() |
Capitalizing the first letter of each word in a string. |
substr($string, $starting_index, $length) |
Returning a part of a string. Example: substr("Hello World!", 6, 5); (returns: "World" ). |
strpos($string, $substring) |
Finding the position of the first occurrence of a substring in a string (the index of the substring's first letter). If there are more than one - the index of the first one encountered. Example: strpos("Hello World!", "World"); (returns: 6 ). |
explode($delimiter, $string) |
Breaking a string into an array by dividing it every time a given delimiter is encountered. Example: explode(",", "apple,banana,cherry"); (returns: ["apple", "banana", "cherry"] ). |
implode($delimiter, $array) |
Joining the elements of an array into a single string by inserting a delimiter between each element. Example: implode("-", ["apple", "banana", "cherry"]); (returns: "apple-banana-cherry" ). |
str_replace($search, $replacement, $string) |
Replacing all occurrences of a substring with another substring. Example: str_replace("apples", "oranges", "I like apples."); (returns: "I like oranges." ). |
str_repeat($string, $times) |
Repeating a string a specified number of times. Example: str_repeat("abc", 3); (returns: "abcabcabc" ). |
str_pad($string, $length, $pad_string, $pad_type) |
Padding a string to a certain length with another string. Example: str_pad("123", 5, "0", STR_PAD_LEFT); (returns: "00123" ). |
str_split($string, $length) |
Splitting a string into an array of substrings, where each substring has a specified maximum length. Example: str_split("Hello", 2); (returns: ["He", "ll", "o"] ). |
Writing to a file
The file_put_contents()
method is used to write data to a file. If the file does not exist, it will be created. We can also use this method to overwrite existing files or append data based on the optional flags provided. Writing to a file: file_put_contents($file_name, $content);
. Appending to a file: file_put_contents($file_name, $content, FILE_APPEND);
. The file_get_contents()
method is used to read from a file ($content = file_get_contents($file_name);
);