
PHP Control Flow, Functions, Arrays, Superglobals, and RegEx
After learning the first PHP basics such as syntax, variables, data types, strings, numbers, casting, math, and constants, the next step is understanding how PHP controls logic and organizes code.
This article explains important PHP topics including operators, if else and elseif conditions, switch statements, match expressions, loops, functions, arrays, superglobals, regular expressions, and PHP RegEx functions.
These topics are essential because they allow developers to make decisions, repeat tasks, reuse code, store collections of data, handle user input, and validate text patterns in real web applications.
PHP Operators
Operators are symbols used to perform operations on values and variables. PHP provides several types of operators for calculations, comparisons, assignments, logic, strings, and arrays.
Arithmetic operators are used for mathematical calculations.
<?php
$a = 10;
$b = 3;
echo $a + $b; // Addition
echo $a - $b; // Subtraction
echo $a * $b; // Multiplication
echo $a / $b; // Division
echo $a % $b; // Modulus
?>Assignment operators are used to assign or update values.
<?php
$total = 100;
$total += 50; // Same as: $total = $total + 50
$total -= 20; // Same as: $total = $total - 20
echo $total;
?>Comparison operators are used to compare two values. They usually return a boolean result: true or false.
<?php
$age = 20;
var_dump($age == 20); // Equal
var_dump($age === 20); // Identical: same value and same type
var_dump($age != 18); // Not equal
var_dump($age > 18); // Greater than
var_dump($age < 30); // Less than
?>Logical operators are used to combine conditions.
<?php
$isLoggedIn = true;
$isAdmin = false;
if ($isLoggedIn && $isAdmin) {
echo "Admin area";
}
if ($isLoggedIn || $isAdmin) {
echo "Access may be allowed";
}
?>String operators are used to combine text. The dot operator . is used for string concatenation.
<?php
$firstName = "Adnan";
$lastName = "Mehrat";
echo $firstName . " " . $lastName;
?>Operators are used almost everywhere in PHP, especially in calculations, conditions, validation, loops, and dynamic page generation.
PHP If...Else...Elseif
The if, else, and elseif statements are used to make decisions in PHP. They allow the program to run different code depending on different conditions.
The basic structure starts with if. If the condition is true, the code inside the block runs.
<?php
$age = 18;
if ($age >= 18) {
echo "You are an adult.";
}
?>The else block runs when the condition is false.
<?php
$age = 16;
if ($age >= 18) {
echo "You are an adult.";
} else {
echo "You are under 18.";
}
?>The elseif block is used when there are multiple possible conditions.
<?php
$score = 75;
if ($score >= 90) {
echo "Excellent";
} elseif ($score >= 70) {
echo "Good";
} elseif ($score >= 50) {
echo "Passed";
} else {
echo "Failed";
}
?>Conditions are very common in real PHP projects. They can be used to check login status, validate form input, show different messages, control permissions, and handle application logic.
PHP Switch
The switch statement is another way to handle multiple possible values. It is useful when one variable can have several known values.
Instead of writing many elseif statements, switch can make the code cleaner in some cases.
<?php
$role = "editor";
switch ($role) {
case "admin":
echo "Full access";
break;
case "editor":
echo "Can edit content";
break;
case "user":
echo "User dashboard";
break;
default:
echo "Unknown role";
}
?>The break keyword is important because it stops PHP from continuing to the next case after a match is found.
The default block runs when none of the cases match. It is similar to the final else in an if statement.
Switch is often used for status values, roles, selected options, page actions, and simple routing-like logic.
PHP Match
The match expression is a modern PHP feature that can be used as a cleaner alternative to switch in many situations.
Unlike switch, match returns a value directly. It also uses strict comparison, which means the value and type must match.
<?php
$status = 200;
$message = match ($status) {
200 => "Success",
404 => "Not Found",
500 => "Server Error",
default => "Unknown Status",
};
echo $message;
?>Match is useful when you want to assign a value based on another value. It often produces shorter and cleaner code than switch.
Another advantage is that match does not need break statements because it returns the matched result directly.
<?php
$userType = "premium";
$discount = match ($userType) {
"free" => 0,
"standard" => 10,
"premium" => 25,
default => 0,
};
echo $discount;
?>Match is commonly used in modern PHP applications when mapping statuses, user roles, types, labels, configuration values, and responses.
PHP Loops
Loops are used to repeat code multiple times. They are useful when working with lists, arrays, counters, repeated HTML elements, database records, or any task that needs repetition.
PHP supports several loop types, including for, while, do while, and foreach.
The for loop is commonly used when you know how many times the loop should run.
<?php
for ($i = 1; $i <= 5; $i++) {
echo "Number: " . $i;
}
?>The while loop runs as long as the condition remains true.
<?php
$count = 1;
while ($count <= 5) {
echo $count;
$count++;
}
?>The do while loop runs at least once, even if the condition is false, because the condition is checked after the first execution.
<?php
$count = 1;
do {
echo $count;
$count++;
} while ($count <= 5);
?>The foreach loop is especially important in PHP because it is used to loop through arrays.
<?php
$languages = ["PHP", "JavaScript", "Python"];
foreach ($languages as $language) {
echo $language;
}
?>Loops are used heavily in real projects. For example, a blog page may use a loop to display articles, an admin panel may use a loop to display users, and an e-commerce page may use a loop to display products.
PHP Functions
Functions are reusable blocks of code. Instead of writing the same logic many times, you can write it once inside a function and call it whenever needed.
A function usually has a name, optional parameters, and an optional return value.
<?php
function sayHello() {
echo "Hello, PHP!";
}
sayHello();
?>Functions can receive parameters. Parameters allow you to pass data into the function.
<?php
function greetUser($name) {
echo "Hello, " . $name;
}
greetUser("Adnan");
?>Functions can also return values. Returning a value is useful when you want the function to calculate or prepare something and give the result back.
<?php
function calculateTotal($price, $quantity) {
return $price * $quantity;
}
$total = calculateTotal(25, 3);
echo $total;
?>Functions help make code cleaner, easier to test, and easier to maintain. In larger projects, functions are often replaced or organized inside classes and methods, but the basic idea remains important.
PHP Arrays
Arrays are used to store multiple values in one variable. Instead of creating many separate variables, an array can hold a collection of related data.
PHP supports indexed arrays, associative arrays, and multidimensional arrays.
An indexed array uses numeric indexes.
<?php
$skills = ["PHP", "Laravel", "MySQL"];
echo $skills[0]; // PHP
echo $skills[1]; // Laravel
?>An associative array uses named keys instead of numeric indexes.
<?php
$user = [
"name" => "Adnan",
"role" => "Developer",
"country" => "Turkey"
];
echo $user["name"];
echo $user["role"];
?>A multidimensional array contains arrays inside another array.
<?php
$users = [
[
"name" => "Adnan",
"role" => "Admin"
],
[
"name" => "Noor",
"role" => "User"
]
];
echo $users[0]["name"];
?>Arrays are extremely important in PHP. They are used to handle form data, API responses, configuration values, database results, menus, categories, permissions, and many other structures.
PHP Superglobals
Superglobals are built-in PHP variables that are always available in all scopes. They allow developers to access request data, form input, server information, sessions, cookies, files, and environment values.
Common PHP superglobals include:
$_GET: contains data sent through the URL query string.
$_POST: contains data sent through an HTTP POST request, usually from forms.
$_REQUEST: may contain data from GET, POST, and COOKIE depending on configuration.
$_SERVER: contains server and request information.
$_SESSION: stores session data for the current user.
$_COOKIE: contains cookie values sent by the browser.
$_FILES: contains uploaded file information.
$_ENV: contains environment variables.
$GLOBALS: contains references to global variables.
For example, $_GET can read values from a URL.
<?php
// Example URL: page.php?name=Adnan
$name = $_GET["name"];
echo $name;
?>The $_POST superglobal is commonly used with forms.
<?php
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$email = $_POST["email"];
echo $email;
}
?>Superglobals are powerful, but they must be used carefully. Data coming from users should always be validated and sanitized before being stored, displayed, or used in database queries.
PHP RegEx
RegEx, short for regular expression, is a pattern-matching system used to search, validate, and manipulate text.
Regular expressions are useful when you need to check whether a text follows a specific format. For example, you may use RegEx to validate an email, check a phone number, search for words, or extract parts of a string.
A simple regular expression pattern may look like this:
/php/iIn this pattern, php is the text we are searching for, and i means case-insensitive search. This means it can match PHP, php, Php, or pHp.
Another example can check whether a string contains only digits.
/^[0-9]+$/This pattern means:
^ marks the start of the string.
[0-9] means any digit from 0 to 9.
+ means one or more characters.
$ marks the end of the string.
RegEx is very useful, but it can become difficult to read when patterns become complex. For this reason, developers should keep patterns clear and test them carefully.
PHP RegEx Functions
PHP provides built-in functions for working with regular expressions. The most common functions are preg_match(), preg_match_all(), preg_replace(), preg_split(), and preg_grep().
The preg_match() function checks whether a pattern exists in a string.
<?php
$text = "Learning PHP is useful.";
if (preg_match("/php/i", $text)) {
echo "The word PHP was found.";
}
?>The preg_match_all() function finds all matches of a pattern.
<?php
$text = "PHP and JavaScript are popular. PHP is used for backend.";
preg_match_all("/php/i", $text, $matches);
print_r($matches);
?>The preg_replace() function replaces text that matches a pattern.
<?php
$text = "I like Java.";
$result = preg_replace("/Java/", "PHP", $text);
echo $result;
?>The preg_split() function splits a string using a regular expression pattern.
<?php
$text = "PHP, Laravel; Symfony Node.js";
$items = preg_split("/[,; ]+/", $text);
print_r($items);
?>The preg_grep() function filters array values that match a pattern.
<?php
$emails = [
"admin@example.com",
"wrong-email",
"user@test.com"
];
$validEmails = preg_grep("/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$/", $emails);
print_r($validEmails);
?>RegEx functions are commonly used in form validation, search features, filtering, text cleanup, routing, log analysis, and data extraction.
How These PHP Concepts Work Together
In real PHP applications, these concepts are usually used together. Operators compare values, conditions decide what should happen, loops repeat tasks, functions organize reusable logic, arrays store data, superglobals receive input, and RegEx validates text.
For example, a contact form may use $_POST to receive input, RegEx to validate the email format, conditions to check errors, arrays to store validation messages, and functions to organize the validation logic.
<?php
function isValidEmail($email) {
return preg_match("/^[\w.-]+@[\w.-]+\.[a-zA-Z]{2,}$/", $email);
}
$errors = [];
if ($_SERVER["REQUEST_METHOD"] === "POST") {
$email = $_POST["email"] ?? "";
if (!isValidEmail($email)) {
$errors[] = "Invalid email address.";
}
if (count($errors) === 0) {
echo "Form submitted successfully.";
} else {
foreach ($errors as $error) {
echo $error;
}
}
}
?>This example combines functions, arrays, superglobals, operators, conditions, loops, and RegEx in one practical structure.
Conclusion
PHP operators, conditions, switch, match, loops, functions, arrays, superglobals, RegEx, and RegEx functions are core concepts that every PHP beginner should understand.
These topics help developers write dynamic and organized code. They are used in almost every real PHP project, from simple websites to large backend applications.
After understanding these concepts, the next step is to practice with forms, validation, file handling, database connections, sessions, object-oriented programming, and frameworks such as Laravel.

