- What is foreach used for in PHP
- When should you use pass-by-reference arguments in PHP
- What is … used for in PHP
- What happens if the variadic operator is placed before another parameter in a PHP function
- What does strict mode do in PHP
- What are return type declarations in PHP
- What are the different types of arrays in PHP
- What is the difference between indexed and associative arrays
- How do you add and remove elements from an array
- What is the difference between array_merge and the + operator
- How does PHP handle array copying
- What is the difference between in_array and array_search
- What is the difference between isset and array_key_exists
- What are array_map and array_filter used for
- What is the difference between sort and asort
- How do you remove duplicate values from an array
- What is a common mistake with array_search
- How do you loop through an array efficiently
- What is the difference between count and sizeof
- How do you check if a variable is an array
- What is the difference between array_slice and array_splice
- What are superglobals in PHP
- What are the main PHP superglobals
- What is $GLOBALS used for
- What is $_SERVER used for
- What is the difference between $_GET and $_POST
- What is $_REQUEST
- What is $_FILES used for
- What is $_SESSION used for
- What is $_COOKIE used for
- What is $_ENV used for
- What is a common security issue with superglobals
- What is the difference between $GLOBALS and global keyword
- How do you secure data coming from $_GET or $_POST
- What is a regular expression in PHP
- What are the main regex functions in PHP
- What does preg_match do
- What is the difference between preg_match and preg_match_all
- What does preg_replace do
- What does preg_split do
- What does preg_grep do
- What are delimiters in regex
- What does the i modifier do
- What does ^ and $ mean
- What is the difference between . and .*
- What is a common mistake in regex
- What is the difference between greedy and lazy matching
- What is a form in PHP
- What is the difference between GET and POST in forms
- What is the action attribute in a form
- What is the method attribute in a form
- How do you access form data in PHP
- What is a common security issue with forms
- How do you validate form data in PHP
- What is the difference between client-side and server-side validation
- What is CSRF and how do you prevent it
- What is XSS and how do you prevent it
- What is enctype in forms
- What is the role of $_FILES in forms
- What is a common mistake when handling forms
- What is the PRG pattern
- What are date and time functions in PHP
- What does date() function do
- What is a timestamp in PHP
- What is the difference between date() and DateTime
- How do you set timezone in PHP
- What does strtotime() do
- How do you add or subtract time
- What is DateInterval
- What is DatePeriod
- What is the difference between gmdate and date
- What is a common mistake with date and time
- What is the difference between include and require in PHP
- When should you use include
- When should you use require
- What are include_once and require_once
- What is a common mistake with include and require
- What is a file in PHP
- How do you open a file in PHP
- What are common file modes
- How do you read a file
- How do you write to a file
- How do you close a file
- What is file_get_contents
- What is file_put_contents
- What is a common mistake with file handling
- What are cookies and sessions in PHP
- What is a cookie
- How do you access cookies
- What is a session
- How do you access session data
- What is the difference between cookies and sessions
- What is a common security issue with cookies
- How do you destroy a session
- What is a common mistake with sessions
What is foreach used for in PHP
foreach is used to iterate over arrays and objects. It loops through each element without using an index.
Basic use with values
$nums = [1, 2, 3];
foreach ($nums as $num) {
echo $num;
}
Use with keys and values
$user = ["name" => "Amr", "age" => 23];
foreach ($user as $key => $value) {
echo $key . ": " . $value;
}
Modify array values using reference
$nums = [1, 2, 3];
foreach ($nums as &$num) {
$num *= 2;
}
unset($num);
Use with objects
class User {
public $name = "Amr";
public $age = 23;
}
$user = new User();
foreach ($user as $key => $value) {
echo $key . ": " . $value;
}
Nested arrays
$data = [[1,2], [3,4]];
foreach ($data as $row) {
foreach ($row as $item) {
echo $item;
}
}
Common mistake
$arr = [1, 2, 3];
foreach ($arr as $v) {
$v += 10;
}
print_r($arr);
Output
[1, 2, 3]
$v is a copy, not a reference
When should you use pass-by-reference arguments in PHP
Use it when the function must modify the original variable
- The function updates the caller’s data
- You want side effects by design
function increment(&$x) {
$x++;
}
$a = 5;
increment($a);
echo $a; // 6
Use it to avoid copying large data
- Large arrays or structures
- Tight loops or heavy processing
function normalize(array &$items) {
foreach ($items as &$v) {
$v = trim($v);
}
unset($v);
}
Use it to return multiple results without arrays
- Cleaner when outputs are few and known
function stats($a, $b, &$sum, &$diff) {
$sum = $a + $b;
$diff = $a - $b;
}
When not to use it
- Simple values
- Public APIs where side effects confuse users
- When immutability improves safety
Key points
- Default is copy-on-write
- Reference uses & and shares the same value
- Changes affect the original variable
Common mistake
- Forgetting that references persist
foreach ($arr as &$v) {}
unset($v);
What is … used for in PHP
It is the spread and variadic operator
Use case 1 Variadic functions
Accept a variable number of arguments
function sum(...$numbers) {
return array_sum($numbers);
}
echo sum(1, 2, 3, 4); // 10
$numbers becomes an array
Use case 2 Argument unpacking
Pass array values as separate arguments
function add($a, $b, $c) {
return $a + $b + $c;
}
$nums = [1, 2, 3];
echo add(...$nums); // 6
Use case 3 Array spreading
Merge arrays
$a = [1, 2]; $b = [3, 4]; $result = [...$a, ...$b]; print_r($result);
Key idea
In function definition it collects arguments
In function call or array it expands values
Common mistake
add(...[1,2]); // error
Quick check
function test($a, ...$b) {
return count($b);
}
echo test(1,2,3,4);
3
What happens if the variadic operator is placed before another parameter in a PHP function
It causes a fatal error because the variadic parameter must be the last parameter in the function signature
What does strict mode do in PHP
Strict mode enforces strict type checking in PHP. When enabled using declare(strict_types=1), PHP will not perform type coercion for function arguments or return values. This means values must match the declared types exactly, otherwise a TypeError is thrown. It applies per file and helps catch bugs early by preventing implicit type conversion.
What are return type declarations in PHP
Return type declarations specify the expected type of value a function must return. You define it after the function signature using a colon followed by the type. PHP enforces that the returned value matches this type, otherwise it throws a TypeError. This improves code reliability and makes function behavior clear.
function add(int $a, int $b): int {
return $a + $b;
}
What are the different types of arrays in PHP
PHP supports indexed arrays, associative arrays, and multidimensional arrays
What is the difference between indexed and associative arrays
Indexed arrays use numeric keys while associative arrays use named keys
How do you add and remove elements from an array
Use [] or array_push to add and unset or array_pop to remove
What is the difference between array_merge and the + operator
array_merge reindexes numeric keys and overwrites string keys while + keeps original keys and ignores duplicates
How does PHP handle array copying
Arrays use copy-on-write so no real copy happens until modification
What is the difference between in_array and array_search
in_array returns a boolean while array_search returns the key or false
What is the difference between isset and array_key_exists
isset returns false if the value is null while array_key_exists checks if the key exists regardless of value
What are array_map and array_filter used for
array_map applies a function to each element while array_filter filters elements based on a condition
What is the difference between sort and asort
sort reindexes and sorts values while asort keeps keys and sorts values
How do you remove duplicate values from an array
Use array_unique
What is a common mistake with array_search
Using == instead of === because 0 can be treated as false
How do you loop through an array efficiently
Use foreach for simplicity and fewer errors
What is the difference between count and sizeof
No difference since sizeof is an alias of count
How do you check if a variable is an array
Use is_array
What is the difference between array_slice and array_splice
array_slice returns a portion without modifying the original while array_splice modifies the original array
What will this return
$arr = [1,2,3]; $arr2 = $arr; $arr2[0] = 100; print_r($arr);
[1,2,3]
What are superglobals in PHP
Superglobals are predefined global arrays that are accessible from any scope in a PHP script
What are the main PHP superglobals
$GLOBALS, $_SERVER, $_GET, $_POST, $_REQUEST, $_FILES, $_COOKIE, $_SESSION, $_ENV
What is $GLOBALS used for
It stores all global variables and allows access to them inside functions
What is $_SERVER used for
It contains server and request information like headers, script path, and request method
What is the difference between $_GET and $_POST
$_GET sends data via URL while $_POST sends data in the request body
What is $_REQUEST
It is a combination of $_GET, $_POST, and $_COOKIE but its usage is not recommended due to ambiguity
What is $_FILES used for
It handles file uploads and provides file name, type, size, and temporary path
What is $_SESSION used for
It stores user data across multiple pages on the server side
What is $_COOKIE used for
It stores small pieces of data on the client side in the browser
What is $_ENV used for
It contains environment variables from the server
What is a common security issue with superglobals
Trusting user input directly without validation or sanitization
What is the difference between $GLOBALS and global keyword
$GLOBALS is an array to access global variables while global keyword imports them into local scope
How do you secure data coming from $_GET or $_POST
Use validation, sanitization, and prepared statements to prevent attacks like SQL injection and XSS
What is a regular expression in PHP
A regular expression is a pattern used to match, search, and manipulate strings
What are the main regex functions in PHP
preg_match, preg_match_all, preg_replace, preg_split, preg_grep
What does preg_match do
It checks if a pattern matches a string and returns 1 or 0
preg_match("/php/i", "I love PHP");
What is the difference between preg_match and preg_match_all
preg_match returns the first match
preg_match_all returns all matches
What does preg_replace do
It replaces matches with a new value
echo preg_replace("/dog/", "cat", "dog is here");
What does preg_split do
It splits a string using a regex pattern
print_r(preg_split("/,/", "a,b,c"));
What does preg_grep do
It filters array elements based on a regex pattern
What are delimiters in regex
They are characters that wrap the pattern like /pattern/
What does the i modifier do
Makes the pattern case insensitive
What does ^ and $ mean
^ matches start of string
$ matches end of string
What is the difference between . and .*
. matches a single character
.* matches zero or more characters
What is a common mistake in regex
Forgetting to escape special characters like . or *
What is the difference between greedy and lazy matching
Greedy matches as much as possible
Lazy matches as little as possible
What will this return
preg_match("/^a/", "apple");
1
What is a form in PHP
A form is used to collect user input and send it to the server for processing
What is the difference between GET and POST in forms
GET sends data in the URL and is limited in size
POST sends data in the request body and supports larger data
What is the action attribute in a form
It defines the URL where the form data is sent
What is the method attribute in a form
It defines how the data is sent, usually GET or POST
How do you access form data in PHP
Using $_GET or $_POST depending on the method
$name = $_POST['name'];
What is a common security issue with forms
Trusting user input without validation or sanitization
How do you validate form data in PHP
Check required fields, data types, and formats using functions like filter_var
What is the difference between client-side and server-side validation
Client-side runs in the browser
Server-side runs in PHP and is required for security
What is CSRF and how do you prevent it
CSRF is a request forgery attack
Prevent it using tokens stored in session and validated on submit
What is XSS and how do you prevent it
XSS injects malicious scripts
Prevent it using htmlspecialchars when outputting data
echo htmlspecialchars($input, ENT_QUOTES, 'UTF-8');
What is enctype in forms
It defines how form data is encoded
multipart/form-data is required for file uploads
What is the role of $_FILES in forms
It handles uploaded files and provides file details
What is a common mistake when handling forms
Not validating or sanitizing input before using it
What is the PRG pattern
Post Redirect Get prevents form resubmission by redirecting after POST
What will this return
if (empty($_POST['name'])) {
echo "Required";
}
Required if name is empty or not set
What are date and time functions in PHP
They are used to create, format, and manipulate dates and times
What does date() function do
Formats a timestamp into a readable date string
echo date("Y-m-d"); // 2026-05-02
What is a timestamp in PHP
It is the number of seconds since January 1 1970
echo time();
What is the difference between date() and DateTime
date() is procedural and simple
DateTime is object-oriented and more flexible
$dt = new DateTime();
echo $dt->format("Y-m-d");
How do you set timezone in PHP
Use date_default_timezone_set
date_default_timezone_set("Europe/Berlin");
What does strtotime() do
Converts a readable date string into a timestamp
echo strtotime("next Monday");
How do you add or subtract time
Use strtotime or DateTime modify
echo date("Y-m-d", strtotime("+1 day"));
What is DateInterval
Represents a time interval
$dt = new DateTime();
$dt->add(new DateInterval("P1D"));
What is DatePeriod
Used to iterate over a range of dates
What is the difference between gmdate and date
date uses local timezone
gmdate uses UTC
What is a common mistake with date and time
Not setting timezone which leads to wrong values
What will this return
echo date("Y", strtotime("2000-01-01"));
2000
What is the difference between include and require in PHP
Both are used to include files but they handle errors differently. include shows a warning if the file is missing and the script continues while require throws a fatal error and stops execution
When should you use include
Use it for optional files where failure should not stop the script
When should you use require
Use it for critical files like config or core logic that must exist
What are include_once and require_once
They ensure the file is included only once and prevent duplicate declarations
What is a common mistake with include and require
Including the same file multiple times without using _once which can cause redeclaration errors
What will happen here
require "config.php"; require "config.php";
Fatal error if config.php defines functions or classes again
What is a file in PHP
A file is a resource used to store data that PHP can read from or write to on the server
How do you open a file in PHP
Use fopen with a file path and mode
$file = fopen("test.txt", "r");
What are common file modes
r read only
w write and overwrite
a append
x create new file
r+ read and write
How do you read a file
Use fread or fgets
$content = fread($file, filesize("test.txt"));
How do you write to a file
Use fwrite
fwrite($file, "Hello");
How do you close a file
Use fclose
fclose($file);
What is file_get_contents
Reads entire file into a string
echo file_get_contents("test.txt");
What is file_put_contents
Writes data to a file in one step
file_put_contents("test.txt", "Hello");
What is a common mistake with file handling
Not checking if the file exists or if fopen failed
What will this return
echo file_exists("test.txt");
true or false depending on file existence
What are cookies and sessions in PHP
They are used to store user data across requests. Cookies store data on the client side while sessions store data on the server side
What is a cookie
A small piece of data stored in the browser and sent with each request
setcookie("user", "Amr", time() + 3600);
How do you access cookies
Using $_COOKIE
echo $_COOKIE['user'];
What is a session
A server-side storage mechanism that keeps user data across multiple pages
session_start(); $_SESSION['user'] = "Amr";
How do you access session data
Using $_SESSION after calling session_start
What is the difference between cookies and sessions
Cookies are stored on the client and can be modified by the user
Sessions are stored on the server and are more secure
What is a common security issue with cookies
Storing sensitive data without encryption
How do you destroy a session
Use session_unset and session_destroy
session_start(); session_unset(); session_destroy();
What is a common mistake with sessions
Forgetting to call session_start before using $_SESSION
What is the role of session ID
It identifies the user session and is usually stored in a cookie
Continue Your PHP Interview Preparation
If you found this guide helpful, don’t miss the rest of our comprehensive PHP interview series:
- 👉 PHP Interview Questions Part 1
- 👉 PHP Interview Questions Part 2
- 👉 PHP Interview Questions Part 3
- 👉 PHP Interview Questions Part 4
By going through the full series, you’ll build a strong foundation in PHP and be fully prepared to tackle interviews with confidence.
No Comments