Interview Preparation
Practice real interview questions with detailed answers
287 Questions
Easy
103 questions
PHP
#1.1
Q1:
What does PHP stand for?
Ans:
PHP originally stood for 'Personal Home Page' and now stands for 'PHP: Hypertext Preprocessor', a recursive acronym.
PHP
#1.2
Q2:
What type of language is PHP?
Ans:
PHP is a server-side scripting language mainly used for web development, but it can also be used as a general-purpose programming language.
PHP
#1.3
Q3:
How do you write a basic PHP script?
Ans:
A PHP script starts with the opening tag . Code is written between these tags.
Code Example
<?php
echo 'Hello World';
?>
PHP
#1.4
Q4:
How do you add comments in PHP?
Ans:
Single line comments use // or #, and multi-line comments use /* ... */.
Code Example
// single line
# also single line
/* multi
line */
PHP
#1.5
Q5:
What is the correct file extension for PHP files?
Ans:
PHP files use the .php extension.
PHP
#1.6
Q6:
How do you print output in PHP?
Ans:
You can use echo or print to output data. echo can take multiple parameters while print returns a value of 1 and takes only one argument.
Code Example
echo 'Hello', ' ', 'World';
print('Hello World');
PHP
#1.7
Q7:
What is the difference between echo and print?
Ans:
echo has no return value and can output multiple comma-separated values, while print returns 1 and only accepts a single argument. echo is generally slightly faster.
PHP
#1.8
Q8:
How do you declare a variable in PHP?
Ans:
Variables in PHP start with a dollar sign ($) followed by the variable name, and do not need explicit type declaration.
Code Example
$name = 'John';
$age = 25;
PHP
#1.9
Q9:
Are PHP variable names case sensitive?
Ans:
Yes, PHP variable names are case sensitive, so $name and $Name are treated as different variables. Function names, however, are not case sensitive.
PHP
#1.10
Q10:
What are the rules for naming PHP variables?
Ans:
A variable name must start with a letter or underscore, followed by any number of letters, numbers, or underscores; it cannot start with a number.
PHP
#1.11
Q11:
What is the difference between single and double quoted strings?
Ans:
Double quoted strings parse variables and escape sequences (like \n), while single quoted strings treat content mostly literally without variable interpolation.
Code Example
$name='Tom';
echo "Hi $name"; // Hi Tom
echo 'Hi $name'; // Hi $name
PHP
#1.12
Q12:
How do you concatenate strings in PHP?
Ans:
You use the dot (.) operator to concatenate strings.
Code Example
$full = 'Hello' . ' ' . 'World';
PHP
#1.13
Q13:
What is a constant in PHP and how is it defined?
Ans:
A constant is a name for a value that cannot change during script execution. It is defined using define() or the const keyword.
Code Example
define('SITE_NAME', 'MyApp');
const PI = 3.14;
PHP
#1.14
Q14:
How do you check if a variable is set?
Ans:
The isset() function checks whether a variable is declared and is not null.
Code Example
if (isset($name)) { echo 'set'; }
PHP
#1.15
Q15:
What does the empty() function do?
Ans:
empty() checks if a variable is empty, meaning it is unset, null, false, 0, '0', an empty string, or an empty array.
PHP
#1.16
Q16:
How do you remove a variable in PHP?
Ans:
The unset() function destroys the specified variable, freeing its memory.
Code Example
unset($name);
PHP
#1.17
Q17:
What is the purpose of the die() or exit() function?
Ans:
die() and exit() are equivalent functions that terminate script execution immediately, optionally printing a message first.
PHP
#1.18
Q18:
How do you include another PHP file?
Ans:
You can use include, include_once, require, or require_once to import another PHP file's content into the current script.
Code Example
include 'header.php';
PHP
#1.19
Q19:
How do you get PHP configuration settings?
Ans:
You can use phpinfo() to display all configuration settings, or ini_get('setting_name') to retrieve a specific one.
PHP
#1.20
Q20:
What is the PHP superglobal $_SERVER used for?
Ans:
$_SERVER is an array containing information about headers, paths, and script locations, such as $_SERVER['REQUEST_METHOD'] or $_SERVER['HTTP_HOST'].
PHP
#1.21
Q21:
How do you find the PHP version currently running?
Ans:
You can use the phpversion() function or run 'php -v' from the command line.
Code Example
echo phpversion();
PHP
#1.22
Q22:
What is the use of the ternary operator in PHP?
Ans:
The ternary operator (condition ? value_if_true : value_if_false) is a shorthand for an if-else statement that returns one of two values.
Code Example
$status = ($age >= 18) ? 'Adult' : 'Minor';
PHP
#1.23
Q23:
What are the data types supported by PHP?
Ans:
PHP supports scalar types (int, float, string, bool), compound types (array, object, callable, iterable), and special types (resource, null).
PHP
#1.24
Q24:
How do you check the data type of a variable?
Ans:
You can use gettype() to get the type as a string, or is_int(), is_string(), is_array(), etc. for specific type checks.
Code Example
var_dump(gettype(5)); // 'integer'
PHP
#1.25
Q25:
What is the difference between == and === in PHP?
Ans:
== compares values only after type juggling (loose comparison), while === compares both value and type without conversion (strict comparison).
Code Example
var_dump(0 == 'a'); // false in PHP8, true in PHP7
var_dump(1 === '1'); // false
PHP
#1.26
Q26:
What is the difference between != and !==?
Ans:
!= checks value inequality with type coercion, while !== checks both value and type inequality without coercion.
PHP
#1.27
Q27:
What does var_dump() do?
Ans:
var_dump() displays structured information about a variable including its type and value, useful for debugging.
Code Example
var_dump([1, 'two', 3.0]);
PHP
#1.28
Q28:
What is NULL in PHP?
Ans:
NULL is a special data type representing a variable with no value assigned. A variable is null if it has been set to NULL, unset, or never assigned.
PHP
#1.29
Q29:
What is an associative array?
Ans:
An associative array uses named keys (strings) instead of numeric indexes to access its elements.
Code Example
$user = ['name' => 'Alice', 'age' => 30];
PHP
#1.30
Q30:
What is the difference between indexed and associative arrays?
Ans:
Indexed arrays use sequential numeric keys starting from 0, while associative arrays use custom string or non-sequential keys to identify values.
PHP
#1.31
Q31:
What is a multidimensional array?
Ans:
A multidimensional array is an array containing one or more arrays as its elements, allowing storage of data in rows and columns.
Code Example
$matrix = [[1,2],[3,4]];
PHP
#1.32
Q32:
How do you convert a string to a number in PHP?
Ans:
You can cast it using (int) or (float), or use functions like intval() and floatval().
Code Example
$n = (int) '42'; $f = floatval('3.14');
PHP
#1.33
Q33:
What are the different types of operators in PHP?
Ans:
PHP supports arithmetic, assignment, comparison, logical, string, array, increment/decrement, and bitwise operators.
PHP
#1.34
Q34:
What is the modulus operator used for?
Ans:
The % operator returns the remainder of dividing two numbers.
Code Example
echo 10 % 3; // 1
PHP
#1.35
Q35:
What are PHP's control structures?
Ans:
PHP control structures include if/else, switch, while, do-while, for, foreach, and match (PHP 8+).
PHP
#1.36
Q36:
What is the difference between while and do-while loops?
Ans:
A while loop checks the condition before executing the loop body, while a do-while loop executes the body at least once before checking the condition.
Code Example
do { echo $i; $i++; } while ($i < 5);
PHP
#1.37
Q37:
How does a foreach loop work in PHP?
Ans:
foreach iterates over each element of an array or object, optionally exposing both key and value.
Code Example
foreach ($arr as $key => $value) { echo "$key: $value"; }
PHP
#1.38
Q38:
What is the switch statement used for?
Ans:
switch evaluates an expression once and compares it against multiple case values, executing the matching block; it uses loose comparison by default.
Code Example
switch($day){
case 1: echo 'Mon'; break;
default: echo 'Other';
}
PHP
#1.39
Q39:
How do you break out of a loop early?
Ans:
The break statement immediately exits the current loop or switch block, optionally taking a numeric argument to break out of nested loops.
PHP
#1.40
Q40:
What does the continue statement do?
Ans:
continue skips the rest of the current loop iteration and proceeds to the next iteration.
PHP
#1.41
Q41:
How do you define a function in PHP?
Ans:
Functions are defined using the function keyword followed by a name, parameters in parentheses, and a body in braces.
Code Example
function greet($name) {
return "Hello, $name";
}
PHP
#1.42
Q42:
What are default parameter values in PHP functions?
Ans:
You can assign a default value to a parameter so it becomes optional; if the caller omits it, the default is used.
Code Example
function greet($name = 'Guest') { echo $name; }
PHP
#1.43
Q43:
How do you create an array in PHP?
Ans:
Arrays can be created using the array() construct or the shorter [] syntax.
Code Example
$fruits = array('apple', 'banana');
$fruits2 = ['apple', 'banana'];
PHP
#1.44
Q44:
How do you add an element to the end of an array?
Ans:
You can use $array[] = $value or the array_push() function.
Code Example
$arr[] = 'new item';
array_push($arr, 'new item');
PHP
#1.45
Q45:
How do you remove the last element of an array?
Ans:
array_pop() removes and returns the last element of an array.
Code Example
$last = array_pop($arr);
PHP
#1.46
Q46:
How do you remove the first element of an array?
Ans:
array_shift() removes and returns the first element, reindexing the remaining numeric keys.
Code Example
$first = array_shift($arr);
PHP
#1.47
Q47:
How do you add an element to the beginning of an array?
Ans:
array_unshift() adds one or more elements to the start of the array and reindexes numeric keys.
Code Example
array_unshift($arr, 'first');
PHP
#1.48
Q48:
How do you check if a value exists in an array?
Ans:
in_array() checks whether a value exists among the array's elements, returning true or false.
Code Example
if (in_array('apple', $fruits)) { echo 'found'; }
PHP
#1.49
Q49:
How do you check if a key exists in an array?
Ans:
array_key_exists() or isset() can check for a key's presence, though isset() returns false if the key's value is null.
Code Example
if (array_key_exists('name', $user)) { echo 'yes'; }
PHP
#1.50
Q50:
How do you get the number of elements in an array?
Ans:
count() or sizeof() returns the number of elements in an array.
Code Example
echo count($arr);
PHP
#1.51
Q51:
How do you sort an array in descending order?
Ans:
rsort() sorts a numerically indexed array in descending order, and arsort() does so for associative arrays while preserving keys.
PHP
#1.52
Q52:
How do you extract a portion of an array?
Ans:
array_slice() returns a sequence of elements from an array based on offset and length parameters without modifying the original array.
Code Example
$part = array_slice($arr, 1, 2);
PHP
#1.53
Q53:
How do you get only the keys or only the values of an array?
Ans:
array_keys() returns all the keys, and array_values() returns all the values, both as new indexed arrays.
PHP
#1.54
Q54:
How do you find unique values in an array?
Ans:
array_unique() removes duplicate values from an array, comparing items as strings by default.
Code Example
$unique = array_unique([1,2,2,3]);
PHP
#1.55
Q55:
How do you reverse an array?
Ans:
array_reverse() returns a new array with elements in reverse order, optionally preserving keys with a second parameter.
Code Example
$reversed = array_reverse([1,2,3]);
PHP
#1.56
Q56:
How do you check if a variable is an array?
Ans:
is_array() returns true if the given variable is an array.
PHP
#1.57
Q57:
How do you find the length of a string?
Ans:
strlen() returns the number of bytes in a string.
Code Example
echo strlen('Hello'); // 5
PHP
#1.58
Q58:
How do you convert a string to uppercase or lowercase?
Ans:
strtoupper() converts a string to uppercase and strtolower() converts it to lowercase.
PHP
#1.59
Q59:
How do you find a substring within a string?
Ans:
strpos() returns the position of the first occurrence of a substring, or false if not found.
Code Example
$pos = strpos('Hello World', 'World'); // 6
PHP
#1.60
Q60:
What is the difference between strpos() and stripos()?
Ans:
strpos() is case-sensitive while stripos() performs a case-insensitive search for a substring's position.
PHP
#1.61
Q61:
How do you replace text within a string?
Ans:
str_replace() replaces all occurrences of a search string with a replacement string.
Code Example
echo str_replace('World', 'PHP', 'Hello World');
PHP
#1.62
Q62:
How do you extract part of a string?
Ans:
substr() returns a portion of a string starting at a given position with an optional length.
Code Example
echo substr('Hello World', 0, 5); // 'Hello'
PHP
#1.63
Q63:
How do you split a string into an array?
Ans:
explode() splits a string by a delimiter into an array of substrings.
Code Example
$parts = explode(',', 'a,b,c'); // ['a','b','c']
PHP
#1.64
Q64:
How do you join array elements into a string?
Ans:
implode() (also called join()) combines array elements into a single string using a specified separator.
Code Example
echo implode(', ', ['a','b','c']); // 'a, b, c'
PHP
#1.65
Q65:
How do you trim whitespace from a string?
Ans:
trim() removes whitespace (or other specified characters) from both ends of a string; ltrim() and rtrim() trim only the left or right side.
PHP
#1.66
Q66:
How do you format numbers as strings in PHP?
Ans:
number_format() formats a number with grouped thousands and a specified number of decimal points.
Code Example
echo number_format(1234567.891, 2); // '1,234,567.89'
PHP
#1.67
Q67:
How do you repeat a string multiple times?
Ans:
str_repeat() returns a new string consisting of the input string repeated a specified number of times.
Code Example
echo str_repeat('ab', 3); // 'ababab'
PHP
#1.68
Q68:
How do you reverse a string?
Ans:
strrev() returns the string with its characters reversed.
Code Example
echo strrev('hello'); // 'olleh'
PHP
#1.69
Q69:
What is a class in PHP?
Ans:
A class is a blueprint for creating objects, defining properties (attributes) and methods (functions) that describe the object's behavior.
Code Example
class Car {
public string $model;
function drive() { echo 'Driving'; }
}
PHP
#1.70
Q70:
How do you create an object from a class?
Ans:
You use the 'new' keyword followed by the class name and any constructor arguments.
Code Example
$car = new Car();
PHP
#1.71
Q71:
What is a constructor in PHP?
Ans:
The constructor is a special method named __construct() that runs automatically when a new object is instantiated, typically used to initialize properties.
Code Example
class User {
public function __construct(public string $name) {}
}
PHP
#1.72
Q72:
What is inheritance in PHP OOP?
Ans:
Inheritance allows a class (child) to inherit properties and methods from another class (parent) using the extends keyword.
Code Example
class Animal { function eat(){} }
class Dog extends Animal {}
PHP
#1.73
Q73:
What is the difference between public, protected, and private visibility?
Ans:
public members are accessible from anywhere, protected members are accessible within the class and its subclasses, and private members are accessible only within the defining class.
PHP
#1.74
Q74:
What are class constants in PHP?
Ans:
Class constants are defined using the const keyword inside a class and hold values that cannot be changed, accessed via ClassName::CONSTANT.
Code Example
class Circle { const PI = 3.14159; }
PHP
#1.75
Q75:
What is encapsulation in OOP?
Ans:
Encapsulation is the bundling of data and methods within a class while restricting direct access to some components using visibility modifiers like private and protected.
PHP
#1.76
Q76:
What is the instanceof operator used for?
Ans:
instanceof checks whether an object is an instance of a specified class, interface, or subclass.
Code Example
if ($car instanceof Vehicle) { echo 'yes'; }
PHP
#1.77
Q77:
How do you handle exceptions in PHP?
Ans:
You wrap risky code in a try block, catch specific exception types in one or more catch blocks, and optionally use a finally block for cleanup code that always runs.
Code Example
try {
$result = 10 / $divisor;
} catch (DivisionByZeroError $e) {
echo $e->getMessage();
} finally {
echo 'Done';
}
PHP
#1.78
Q78:
How do you open a file in PHP?
Ans:
fopen() opens a file or URL and returns a file handle resource, with a mode parameter like 'r' for read or 'w' for write.
Code Example
$handle = fopen('data.txt', 'r');
PHP
#1.79
Q79:
How do you read the entire contents of a file?
Ans:
file_get_contents() reads an entire file into a string in one call, which is simpler than manually looping with fopen/fread.
Code Example
$content = file_get_contents('data.txt');
PHP
#1.80
Q80:
How do you write data to a file?
Ans:
file_put_contents() writes a string to a file, creating the file if it doesn't exist, and can append using the FILE_APPEND flag.
Code Example
file_put_contents('log.txt', 'Hello', FILE_APPEND);
PHP
#1.81
Q81:
How do you check if a file exists?
Ans:
file_exists() returns true if the specified file or directory exists.
Code Example
if (file_exists('config.php')) { ... }
PHP
#1.82
Q82:
How do you delete a file in PHP?
Ans:
unlink() deletes the specified file from the filesystem.
Code Example
unlink('old_file.txt');
PHP
#1.83
Q83:
What are PHP superglobals?
Ans:
Superglobals are built-in variables always accessible in all scopes, including $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER, $_FILES, $_REQUEST, $_ENV, and $GLOBALS.
PHP
#1.84
Q84:
What is the difference between $_GET and $_POST?
Ans:
$_GET retrieves data sent via URL query parameters and is visible in the URL with limited size, while $_POST retrieves data sent in the HTTP request body, typically used for form submissions and larger or sensitive data.
PHP
#1.85
Q85:
How do you redirect to another page in PHP?
Ans:
You send a Location header before any output using the header() function, followed by exit() to stop further script execution.
Code Example
header('Location: login.php');
exit();
PHP
#1.86
Q86:
How do you start a session in PHP?
Ans:
session_start() must be called before any output to initiate or resume a session, enabling use of the $_SESSION superglobal.
Code Example
session_start();
$_SESSION['user_id'] = 5;
PHP
#1.87
Q87:
How do you destroy a session?
Ans:
session_destroy() removes all session data on the server, often paired with unset($_SESSION) and clearing the session cookie.
Code Example
session_start();
session_unset();
session_destroy();
PHP
#1.88
Q88:
How do you set a cookie in PHP?
Ans:
setcookie() sends a cookie to the client's browser, accepting parameters for name, value, expiration, path, domain, and security flags.
Code Example
setcookie('user', 'John', time() + 3600);
PHP
#1.89
Q89:
How do you read a cookie value?
Ans:
You access it through the $_COOKIE superglobal array using the cookie's name as the key.
Code Example
echo $_COOKIE['user'] ?? 'Guest';
PHP
#1.90
Q90:
How do you connect to a MySQL database using MySQLi?
Ans:
You create a new mysqli object with hostname, username, password, and database name parameters.
Code Example
$conn = new mysqli('localhost', 'user', 'pass', 'mydb');
if ($conn->connect_error) { die($conn->connect_error); }
PHP
#1.91
Q91:
How do you connect to a database using PDO?
Ans:
You instantiate a new PDO object with a DSN string, username, and password, typically wrapped in a try-catch to handle connection errors.
Code Example
try {
$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'user', 'pass');
} catch (PDOException $e) {
echo $e->getMessage();
}
PHP
#1.92
Q92:
How do you fetch results from a PDO query?
Ans:
You call fetch() to get one row at a time, or fetchAll() to retrieve all rows at once, typically specifying a fetch mode like PDO::FETCH_ASSOC.
Code Example
$stmt = $pdo->query('SELECT * FROM users');
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);
PHP
#1.93
Q93:
How do you close a database connection in PHP?
Ans:
You typically set the connection variable to null (for PDO) or call close() on a MySQLi connection object, though PHP closes connections automatically at script end.
PHP
#1.94
Q94:
How do you check if a database query failed in MySQLi?
Ans:
You check the mysqli object's error property or use mysqli_error() after running the query to retrieve the error message.
PHP
#1.95
Q95:
What is the purpose of htmlspecialchars()?
Ans:
htmlspecialchars() converts special characters like <, >, and & into HTML entities, preventing browsers from interpreting user input as executable HTML or script tags.
PHP
#1.96
Q96:
What does the 'i' modifier do in a PHP regex pattern?
Ans:
The 'i' modifier makes the pattern match case-insensitively.
Code Example
preg_match('/hello/i', 'HELLO World'); // matches
PHP
#1.97
Q97:
How do you get the current date and time in PHP?
Ans:
The date() function formats the current timestamp according to a format string, and time() returns the current Unix timestamp.
Code Example
echo date('Y-m-d H:i:s');
PHP
#1.98
Q98:
What is strtotime() used for?
Ans:
strtotime() parses an English textual date/time description into a Unix timestamp.
Code Example
echo date('Y-m-d', strtotime('next Friday'));
PHP
#1.99
Q99:
How do you format a timestamp into a readable date string?
Ans:
The date() function accepts a Unix timestamp and a format string of placeholder characters like Y, m, d, H, i, s to produce a formatted string.
Code Example
echo date('l, F j, Y', time());
PHP
#1.100
Q100:
What is a Unix timestamp?
Ans:
A Unix timestamp is the number of seconds elapsed since January 1, 1970 (the Unix epoch), used internally by PHP to represent points in time.
PHP
#1.101
Q101:
What is Composer in PHP?
Ans:
Composer is PHP's dependency manager, allowing developers to declare, install, and autoload libraries their project depends on via a composer.json file.
PHP
#1.102
Q102:
What is the composer.json file used for?
Ans:
composer.json declares a project's metadata, required dependencies and their version constraints, and autoloading configuration.
Code Example
{
"require": {
"monolog/monolog": "^3.0"
}
}
PHP
#1.103
Q103:
How do you check the type of an object dynamically?
Ans:
get_class() returns the name of an object's class as a string, useful when the class type must be determined at runtime.
Code Example
echo get_class($car); // 'Car'
Medium
146 questions
PHP
#2.1
Q1:
What is the difference between define() and const?
Ans:
const is a language construct evaluated at compile time and used outside functions, while define() is a function evaluated at runtime and can be used conditionally inside functions.
PHP
#2.2
Q2:
What is the difference between isset() and empty()?
Ans:
isset() returns false only if the variable is not set or is null, while empty() also returns true for falsy values like 0, '', and false even if the variable is set.
PHP
#2.3
Q3:
What is the difference between include and require?
Ans:
If the file is not found, include produces a warning and the script continues, while require produces a fatal error and stops script execution.
PHP
#2.4
Q4:
What is the difference between include_once and include?
Ans:
include_once checks whether the file has already been included and skips it if so, preventing redeclaration errors, while include will include the file every time it's called.
PHP
#2.5
Q5:
What is the null coalescing operator?
Ans:
The ?? operator returns its first operand if it exists and is not null, otherwise it returns the second operand; it is a shorthand for isset() checks.
Code Example
$name = $_GET['name'] ?? 'Guest';
PHP
#2.6
Q6:
What is the null coalescing assignment operator?
Ans:
The ??= operator, introduced in PHP 7.4, assigns the right-hand value to the variable only if the variable is null or not set.
Code Example
$data['count'] ??= 0;
PHP
#2.7
Q7:
What is the spaceship operator in PHP?
Ans:
The spaceship operator (<=>) compares two expressions and returns -1, 0, or 1 depending on whether the left operand is less than, equal to, or greater than the right.
Code Example
echo 1 <=> 2; // -1
PHP
#2.8
Q8:
What is type juggling in PHP?
Ans:
Type juggling is PHP's automatic conversion of a variable's data type based on context, such as converting a numeric string to an integer during arithmetic operations.
Code Example
echo '5' + 3; // 8
PHP
#2.9
Q9:
What is type casting in PHP and how is it done?
Ans:
Type casting is explicitly converting a variable to another type by prefixing it with the desired type in parentheses.
Code Example
$num = (int) '123abc'; // 123
PHP
#2.10
Q10:
What is the difference between var_dump() and print_r()?
Ans:
print_r() displays a human-readable representation of a variable's value (mainly arrays/objects) without showing types, while var_dump() shows both the type and value with more detail.
PHP
#2.11
Q11:
How does PHP handle boolean conversion of values like '0' and empty string?
Ans:
In boolean context, 0, '0', '', empty array, and NULL are considered false; all other values, including '0.0' and whitespace strings, are considered true.
PHP
#2.12
Q12:
What is the PHP_EOL constant used for?
Ans:
PHP_EOL is a predefined constant representing the correct end-of-line sequence for the current operating system (\n on Unix, \r\n on Windows).
PHP
#2.13
Q13:
What is the difference between and/or and &&/||?
Ans:
They function the same logically, but && and || have higher precedence than and/or, which can affect how expressions are evaluated, especially with assignment.
PHP
#2.14
Q14:
How does the increment operator behave on strings?
Ans:
PHP's ++ operator can increment alphanumeric strings (e.g., 'a' becomes 'b', 'z' becomes 'aa'), following Perl-style string increment rules.
Code Example
$s = 'a'; $s++; echo $s; // 'b'
PHP
#2.15
Q15:
What is the match expression introduced in PHP 8?
Ans:
match is similar to switch but uses strict comparison, returns a value directly, requires no break statements, and throws an UnhandledMatchError if no case matches.
Code Example
$result = match($status) {
1, 2 => 'active',
0 => 'inactive',
default => 'unknown',
};
PHP
#2.16
Q16:
What is the difference between switch and match?
Ans:
match uses strict (===) comparison and is an expression that returns a value, while switch uses loose comparison, requires break to prevent fall-through, and is a statement.
PHP
#2.17
Q17:
How do you loop through an array by reference using foreach?
Ans:
You prefix the value variable with an ampersand (&) so modifications inside the loop affect the original array.
Code Example
foreach ($arr as &$val) { $val *= 2; }
unset($val);
PHP
#2.18
Q18:
What is the goto statement in PHP?
Ans:
goto allows jumping to another section of code marked by a label; it is rarely used because it can make code harder to follow.
PHP
#2.19
Q19:
What is a variadic function in PHP?
Ans:
A variadic function accepts a variable number of arguments using the ... operator, which collects them into an array.
Code Example
function sum(...$nums) { return array_sum($nums); }
PHP
#2.20
Q20:
How do you pass arguments by reference in PHP?
Ans:
Prefixing a parameter with an ampersand (&) passes it by reference so changes inside the function affect the original variable.
Code Example
function increment(&$num) { $num++; }
PHP
#2.21
Q21:
What is the difference between passing by value and by reference?
Ans:
Passing by value copies the argument so changes inside the function don't affect the original variable, while passing by reference lets the function modify the original variable directly.
PHP
#2.22
Q22:
Can PHP functions return multiple values?
Ans:
PHP functions can return an array or a list, and PHP 7.1+ supports list()/short array destructuring to unpack multiple returned values.
Code Example
function coords() { return [1, 2]; }
[$x, $y] = coords();
PHP
#2.23
Q23:
What is a recursive function?
Ans:
A recursive function is one that calls itself to solve smaller instances of the same problem, typically requiring a base case to stop recursion.
Code Example
function factorial($n) {
return $n <= 1 ? 1 : $n * factorial($n - 1);
}
PHP
#2.24
Q24:
What is an anonymous function (closure) in PHP?
Ans:
An anonymous function is a function without a name, often assigned to a variable or passed as a callback, defined using the function keyword or arrow syntax.
Code Example
$square = function($n) { return $n * $n; };
echo $square(4);
PHP
#2.25
Q25:
What is a closure's 'use' clause for?
Ans:
The use clause allows an anonymous function to inherit variables from the parent scope by value or by reference.
Code Example
$factor = 2;
$multiply = function($n) use ($factor) { return $n * $factor; };
PHP
#2.26
Q26:
What are arrow functions in PHP?
Ans:
Introduced in PHP 7.4, arrow functions (fn) provide a concise syntax and automatically capture outer scope variables by value.
Code Example
$multiply = fn($n) => $n * 2;
PHP
#2.27
Q27:
What is the difference between closures and arrow functions?
Ans:
Arrow functions automatically capture variables from the parent scope without needing 'use', while regular closures must explicitly import outer variables via use(); arrow functions are also limited to a single expression body.
PHP
#2.28
Q28:
What are type declarations (type hints) in PHP functions?
Ans:
Type declarations specify the expected data type of function parameters and return values, enforced at runtime, improving code reliability.
Code Example
function add(int $a, int $b): int {
return $a + $b;
}
PHP
#2.29
Q29:
What is strict_types in PHP?
Ans:
Declaring strict_types=1 at the top of a file enforces strict type checking for scalar type declarations, disabling automatic type coercion in that file.
Code Example
declare(strict_types=1);
PHP
#2.30
Q30:
What are nullable types in PHP?
Ans:
A nullable type is denoted by a question mark before the type (e.g., ?int) indicating the parameter or return value can be either that type or null.
Code Example
function find(?int $id): ?array { ... }
PHP
#2.31
Q31:
What is a callable in PHP?
Ans:
A callable is any PHP value that can be called as a function, such as a string function name, an array [object, method], or a Closure.
PHP
#2.32
Q32:
How do you call a function dynamically using a variable?
Ans:
You can store a function name in a variable and call it by appending parentheses, known as variable functions.
Code Example
function hello() { echo 'Hi'; }
$fn = 'hello';
$fn();
PHP
#2.33
Q33:
What are named arguments in PHP 8?
Ans:
Named arguments allow passing values to a function by specifying the parameter name, so arguments can be supplied in any order and optional ones can be skipped.
Code Example
function createUser(string $name, int $age = 18) {}
createUser(age: 25, name: 'Tom');
PHP
#2.34
Q34:
How do you set a default return type of void in PHP?
Ans:
You declare the function's return type as void to indicate it returns no meaningful value; PHP will error if such a function tries to return a value.
Code Example
function logMessage(string $msg): void {
echo $msg;
}
PHP
#2.35
Q35:
What is the difference between array_merge() and the + operator for arrays?
Ans:
array_merge() re-indexes numeric keys and later values overwrite earlier string keys, while the + operator preserves the original keys and only adds keys from the second array that don't already exist.
Code Example
print_r(array_merge([1,2],[3,4])); // [1,2,3,4]
print_r([1,2] + [0=>9,2=>3]); // [1,2,3]
PHP
#2.36
Q36:
What is the difference between sort() and asort()?
Ans:
sort() sorts values and reindexes keys numerically, while asort() sorts values but preserves the original key-value association.
PHP
#2.37
Q37:
What is the difference between sort() and ksort()?
Ans:
sort() sorts an array by its values, while ksort() sorts an array by its keys, both in ascending order.
PHP
#2.38
Q38:
What does usort() do?
Ans:
usort() sorts an array using a user-defined comparison callback function and reindexes the array's keys.
Code Example
usort($people, fn($a, $b) => $a['age'] <=> $b['age']);
PHP
#2.39
Q39:
What is the difference between usort() and uasort()?
Ans:
usort() reindexes the array after sorting, while uasort() preserves the original keys, making it suitable for associative arrays.
PHP
#2.40
Q40:
What does array_map() do?
Ans:
array_map() applies a callback function to every element of one or more arrays and returns a new array with the results.
Code Example
$squares = array_map(fn($n) => $n * $n, [1,2,3]);
PHP
#2.41
Q41:
What does array_filter() do?
Ans:
array_filter() filters elements of an array using a callback function, returning only elements for which the callback returns true, and preserves original keys.
Code Example
$even = array_filter([1,2,3,4], fn($n) => $n % 2 == 0);
PHP
#2.42
Q42:
What does array_reduce() do?
Ans:
array_reduce() iteratively reduces an array to a single value using a callback function and an optional initial value.
Code Example
$total = array_reduce([1,2,3], fn($carry, $item) => $carry + $item, 0);
PHP
#2.43
Q43:
What is the difference between array_map, array_filter, and array_reduce?
Ans:
array_map transforms every element and returns an array of the same size, array_filter selects a subset of elements based on a condition, and array_reduce collapses the array into a single accumulated value.
PHP
#2.44
Q44:
What is the difference between array_slice() and array_splice()?
Ans:
array_slice() returns a portion of the array without modifying the original, while array_splice() removes and optionally replaces a portion of the array, modifying it in place.
PHP
#2.45
Q45:
How do you combine two arrays into key-value pairs?
Ans:
array_combine() creates an array using one array's values as keys and another array's values as values.
Code Example
$combined = array_combine(['a','b'], [1,2]); // ['a'=>1,'b'=>2]
PHP
#2.46
Q46:
What is the spread operator in array context?
Ans:
The ... operator can unpack an array's elements into another array literal or function call arguments.
Code Example
$a = [1, 2];
$b = [0, ...$a, 3]; // [0,1,2,3]
PHP
#2.47
Q47:
What does array_column() do?
Ans:
array_column() returns the values from a single column of an input array of arrays or objects, optionally indexed by another column.
Code Example
$names = array_column($users, 'name');
PHP
#2.48
Q48:
What is list() used for?
Ans:
list() (or its short syntax []) assigns variables from an array's elements in a single statement, useful for destructuring.
Code Example
[$a, $b] = [1, 2];
PHP
#2.49
Q49:
What is the difference between array_walk() and foreach?
Ans:
array_walk() applies a callback to each element and can pass elements by reference to directly modify the original array, while foreach is a language construct for iteration that requires an explicit reference to modify elements.
PHP
#2.50
Q50:
How do you check if a string starts or ends with a specific substring?
Ans:
str_starts_with() and str_ends_with(), introduced in PHP 8, check whether a string begins or ends with a given substring.
Code Example
var_dump(str_starts_with('hello world', 'hello')); // true
PHP
#2.51
Q51:
How do you check if a string contains a substring?
Ans:
str_contains(), introduced in PHP 8, returns true if the needle string is found within the haystack string.
Code Example
var_dump(str_contains('Hello World', 'World'));
PHP
#2.52
Q52:
How does sprintf() work?
Ans:
sprintf() returns a formatted string according to a format specifier string containing placeholders like %s, %d, or %f.
Code Example
echo sprintf('%s is %d years old', 'Tom', 25);
PHP
#2.53
Q53:
What is the difference between sprintf() and printf()?
Ans:
sprintf() returns the formatted string, while printf() outputs the formatted string directly and returns the length of the output string.
PHP
#2.54
Q54:
How do you pad a string to a certain length?
Ans:
str_pad() pads a string on the left, right, or both sides to a specified length using a given padding string.
Code Example
echo str_pad('5', 3, '0', STR_PAD_LEFT); // '005'
PHP
#2.55
Q55:
What is heredoc and nowdoc syntax?
Ans:
Heredoc (<<
Code Example
$name='World';
echo <<<EOT
Hello $name
EOT;
PHP
#2.56
Q56:
What is a destructor in PHP?
Ans:
The __destruct() method is called automatically when an object is destroyed or the script ends, useful for cleanup tasks.
PHP
#2.57
Q57:
What are constructor property promotion in PHP 8?
Ans:
Constructor property promotion lets you declare and initialize class properties directly in the constructor's parameter list, reducing boilerplate.
Code Example
class Point {
public function __construct(
public float $x,
public float $y
) {}
}
PHP
#2.58
Q58:
What is method overriding in PHP?
Ans:
Method overriding occurs when a child class redefines a method that already exists in its parent class, replacing its behavior.
Code Example
class Animal { function sound(){ echo 'Some sound'; } }
class Cat extends Animal { function sound(){ echo 'Meow'; } }
PHP
#2.59
Q59:
What is an abstract class?
Ans:
An abstract class cannot be instantiated directly and may contain abstract methods that must be implemented by any concrete subclass.
Code Example
abstract class Shape {
abstract public function area(): float;
}
PHP
#2.60
Q60:
What is an interface in PHP?
Ans:
An interface defines a contract of method signatures that implementing classes must provide, without any implementation itself.
Code Example
interface Shape {
public function area(): float;
}
class Circle implements Shape {
public function area(): float { return 3.14 * $this->r ** 2; }
}
PHP
#2.61
Q61:
What is the difference between an abstract class and an interface?
Ans:
An abstract class can have both implemented and abstract methods along with properties and constructors, while an interface only declares method signatures (and constants) and a class can implement multiple interfaces but extend only one class.
PHP
#2.62
Q62:
Can a class implement multiple interfaces in PHP?
Ans:
Yes, a class can implement multiple interfaces separated by commas, though it can only extend a single parent class.
Code Example
class Bird implements Flyable, Swimmable {}
PHP
#2.63
Q63:
What is a trait in PHP?
Ans:
A trait is a mechanism for code reuse that allows methods to be included in multiple classes without using inheritance, addressing PHP's single inheritance limitation.
Code Example
trait Loggable {
function log($msg) { echo $msg; }
}
class Order { use Loggable; }
PHP
#2.64
Q64:
What is a static property or method?
Ans:
Static members belong to the class itself rather than any instance, accessed using the scope resolution operator (::), and shared across all instances.
Code Example
class Counter {
public static int $count = 0;
public static function increment() { self::$count++; }
}
PHP
#2.65
Q65:
What is the purpose of the final keyword?
Ans:
The final keyword prevents a class from being extended or a method from being overridden by child classes.
Code Example
final class Config {}
class Base { final function init(){} }
PHP
#2.66
Q66:
What is an abstract method?
Ans:
An abstract method is declared without a body inside an abstract class or interface, and must be implemented by any non-abstract subclass.
PHP
#2.67
Q67:
What is polymorphism in PHP OOP?
Ans:
Polymorphism allows objects of different classes to be treated through a common interface, with each class providing its own implementation of shared methods.
PHP
#2.68
Q68:
What is the __toString() magic method?
Ans:
__toString() allows an object to be converted to a string representation, automatically called when the object is used in a string context like echo.
Code Example
class Money {
function __toString(): string { return '$' . $this->amount; }
}
PHP
#2.69
Q69:
What is the difference between an object clone and assignment?
Ans:
Assigning an object variable to another copies the reference (both point to the same object), while clone creates a new, independent object with copied properties.
PHP
#2.70
Q70:
What are namespaces in PHP?
Ans:
Namespaces organize code into logical groups and prevent naming collisions between classes, functions, or constants with the same name.
Code Example
namespace App\Models;
class User {}
// usage: new \App\Models\User();
PHP
#2.71
Q71:
What is dependency injection?
Ans:
Dependency injection is a design pattern where an object's dependencies are provided externally (often through the constructor) rather than being created internally, improving testability and decoupling.
Code Example
class OrderService {
public function __construct(private PaymentGateway $gateway) {}
}
PHP
#2.72
Q72:
What is the Singleton design pattern in PHP?
Ans:
Singleton ensures a class has only one instance and provides a global access point to it, typically implemented with a private constructor and a static getInstance() method.
Code Example
class DB {
private static ?DB $instance = null;
private function __construct(){}
public static function getInstance(): DB {
return self::$instance ??= new self();
}
}
PHP
#2.73
Q73:
What are readonly properties in PHP 8.1?
Ans:
Readonly properties can be initialized only once, typically in the constructor, and throw an error if modified afterward, enforcing immutability.
Code Example
class Point {
public function __construct(public readonly int $x, public readonly int $y) {}
}
PHP
#2.74
Q74:
What are enums in PHP 8.1?
Ans:
Enums are a new type that defines a fixed set of possible values (cases) for a variable, improving type safety compared to using class constants.
Code Example
enum Status {
case Active;
case Inactive;
}
$s = Status::Active;
PHP
#2.75
Q75:
What is the difference between a pure enum and a backed enum?
Ans:
A pure enum's cases have no associated scalar value, while a backed enum assigns each case a string or int value that can be retrieved and used for serialization.
Code Example
enum Status: string {
case Active = 'active';
case Inactive = 'inactive';
}
PHP
#2.76
Q76:
What is the difference between an error and an exception in PHP?
Ans:
Errors typically represent serious problems (like fatal errors) historically not catchable, while exceptions are objects representing runtime issues that can be caught with try-catch; since PHP 7, most errors are represented by Error objects implementing Throwable, so both can be caught.
PHP
#2.77
Q77:
How do you throw a custom exception?
Ans:
You create a class extending Exception (or a subclass) and use the throw keyword to raise an instance of it.
Code Example
class InsufficientFundsException extends Exception {}
throw new InsufficientFundsException('Not enough balance');
PHP
#2.78
Q78:
What is the purpose of the finally block?
Ans:
The finally block contains code that executes after the try/catch blocks regardless of whether an exception was thrown or caught, commonly used for cleanup like closing files or connections.
PHP
#2.79
Q79:
Can you catch multiple exception types in a single catch block?
Ans:
Yes, PHP 7.1+ allows specifying multiple exception types separated by a pipe (|) in a single catch block.
Code Example
try {
// code
} catch (TypeError | ValueError $e) {
echo $e->getMessage();
}
PHP
#2.80
Q80:
What methods does the Exception class provide?
Ans:
Common methods include getMessage(), getCode(), getFile(), getLine(), getTrace(), and getTraceAsString() to inspect details about the thrown exception.
PHP
#2.81
Q81:
What is error suppression using the @ operator, and why is it discouraged?
Ans:
Prefixing an expression with @ suppresses any error messages it generates, but it is discouraged because it hides real problems and can make debugging difficult; using proper error handling is preferred.
PHP
#2.82
Q82:
How do you read a file line by line?
Ans:
You can use fgets() in a loop while the file pointer is not at the end (feof()), or use the file() function to read all lines into an array.
Code Example
$handle = fopen('data.txt', 'r');
while (!feof($handle)) {
echo fgets($handle);
}
fclose($handle);
PHP
#2.83
Q83:
How do you upload a file in PHP?
Ans:
Uploaded files are accessible via the $_FILES superglobal, and move_uploaded_file() moves the temporary uploaded file to a permanent destination.
Code Example
move_uploaded_file($_FILES['photo']['tmp_name'], 'uploads/photo.jpg');
PHP
#2.84
Q84:
How do you get information about a file (size, modification time)?
Ans:
filesize() returns the file size in bytes, and filemtime() returns the last modification time as a Unix timestamp.
PHP
#2.85
Q85:
What is the difference between copy() and rename() for files?
Ans:
copy() duplicates a file to a new location while keeping the original, whereas rename() moves or renames a file, removing it from its original location.
PHP
#2.86
Q86:
What is $_REQUEST used for?
Ans:
$_REQUEST is an array containing the contents of $_GET, $_POST, and $_COOKIE combined, though its use is often discouraged due to ambiguity about the data's source.
PHP
#2.87
Q87:
How do you retrieve form data safely in PHP?
Ans:
You should validate and sanitize input using functions like filter_var(), and use htmlspecialchars() when outputting user data to prevent XSS.
Code Example
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
PHP
#2.88
Q88:
What is filter_var() used for?
Ans:
filter_var() filters or validates a variable using a specified filter, such as validating an email address, URL, or integer.
Code Example
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { echo 'valid'; }
PHP
#2.89
Q89:
How do you prevent Cross-Site Scripting (XSS) when displaying user input?
Ans:
You should escape output using htmlspecialchars() or htmlentities() to convert special characters into HTML entities before displaying user-supplied data.
Code Example
echo htmlspecialchars($_POST['comment']);
PHP
#2.90
Q90:
What is $GLOBALS in PHP?
Ans:
$GLOBALS is a superglobal array that provides access to all variables defined in the global scope from within any function.
Code Example
$x = 10;
function show() { echo $GLOBALS['x']; }
PHP
#2.91
Q91:
How do you access command-line arguments in a PHP script?
Ans:
The $argv array holds command-line arguments passed to the script, and $argc holds the count of arguments, available when running PHP via CLI.
PHP
#2.92
Q92:
What is $_ENV used for?
Ans:
$_ENV contains variables provided to the script via the environment, such as environment variables set on the server or in a .env configuration.
PHP
#2.93
Q93:
What is the difference between sessions and cookies?
Ans:
Sessions store data on the server and reference it via a session ID cookie on the client, making them more secure for sensitive data, while cookies store data directly on the client's browser with a size limitation.
PHP
#2.94
Q94:
What are HttpOnly and Secure cookie flags?
Ans:
The HttpOnly flag prevents client-side JavaScript from accessing the cookie, mitigating XSS-based theft, while the Secure flag ensures the cookie is only sent over HTTPS connections.
PHP
#2.95
Q95:
How can you configure session expiration and lifetime?
Ans:
You can adjust settings like session.gc_maxlifetime in php.ini or set a custom cookie lifetime via session_set_cookie_params() before starting the session.
PHP
#2.96
Q96:
What is the difference between MySQLi and PDO?
Ans:
MySQLi only supports MySQL databases and offers both procedural and object-oriented APIs, while PDO supports multiple database drivers (MySQL, PostgreSQL, SQLite, etc.) through a single consistent object-oriented API.
PHP
#2.97
Q97:
What are prepared statements and why are they important?
Ans:
Prepared statements separate SQL logic from data by using placeholders for values, which are bound and sent separately to the database, preventing SQL injection attacks.
Code Example
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
PHP
#2.98
Q98:
How do you execute a prepared statement with named parameters in PDO?
Ans:
You use named placeholders prefixed with a colon in the SQL, then pass an associative array or bindParam/bindValue calls matching those names.
Code Example
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = :email');
$stmt->execute(['email' => $email]);
PHP
#2.99
Q99:
What is SQL injection and how do prepared statements prevent it?
Ans:
SQL injection occurs when untrusted input is concatenated directly into a SQL query, allowing an attacker to alter query logic; prepared statements prevent this by treating user input strictly as data, never as executable SQL code.
PHP
#2.100
Q100:
How do you handle transactions in PDO?
Ans:
You call beginTransaction(), execute multiple queries, then commit() if successful, or rollBack() if an error occurs, ensuring atomicity.
Code Example
$pdo->beginTransaction();
try {
$pdo->exec('UPDATE accounts SET balance = balance - 100 WHERE id = 1');
$pdo->exec('UPDATE accounts SET balance = balance + 100 WHERE id = 2');
$pdo->commit();
} catch (Exception $e) {
$pdo->rollBack();
}
PHP
#2.101
Q101:
How do you get the ID of the last inserted row?
Ans:
In PDO, you call lastInsertId() on the PDO object after an insert statement; in MySQLi, you access the insert_id property.
Code Example
$pdo->lastInsertId();
$conn->insert_id;
PHP
#2.102
Q102:
What is the difference between PDO::FETCH_ASSOC and PDO::FETCH_OBJ?
Ans:
PDO::FETCH_ASSOC returns each row as an associative array keyed by column name, while PDO::FETCH_OBJ returns each row as a stdClass object with column names as properties.
PHP
#2.103
Q103:
What is an ORM and does PHP have popular ones?
Ans:
An ORM (Object-Relational Mapper) maps database tables to classes and rows to objects, abstracting raw SQL; popular PHP ORMs include Eloquent (Laravel) and Doctrine.
PHP
#2.104
Q104:
How do you prevent storing plain text passwords in a database?
Ans:
You should hash passwords using password_hash() before storing them and verify login attempts using password_verify(), never storing or comparing raw passwords.
Code Example
$hash = password_hash($password, PASSWORD_DEFAULT);
if (password_verify($input, $hash)) { echo 'Match'; }
PHP
#2.105
Q105:
What does password_hash() use by default in PHP?
Ans:
By default, password_hash() uses the bcrypt algorithm (PASSWORD_DEFAULT), which automatically generates a secure salt and can be upgraded to stronger algorithms in future PHP versions.
PHP
#2.106
Q106:
What is Cross-Site Scripting (XSS)?
Ans:
XSS is a vulnerability where an attacker injects malicious scripts into web pages viewed by other users, often exploited when user input is rendered without proper escaping.
PHP
#2.107
Q107:
What is Cross-Site Request Forgery (CSRF) and how do you prevent it?
Ans:
CSRF tricks an authenticated user's browser into submitting unwanted requests to a site; it is mitigated by including a unique, unpredictable CSRF token in forms that is validated on submission.
PHP
#2.108
Q108:
What is SQL Injection?
Ans:
SQL Injection is an attack where malicious SQL is inserted into a query through unsanitized user input, potentially allowing data theft or manipulation; it is prevented using prepared statements.
PHP
#2.109
Q109:
How do you securely store passwords in PHP applications?
Ans:
Passwords should be hashed with password_hash() using a strong algorithm like bcrypt or Argon2, never encrypted or stored in plain text, and verified with password_verify().
PHP
#2.110
Q110:
What is the difference between htmlspecialchars() and strip_tags()?
Ans:
htmlspecialchars() encodes special characters so tags display as text rather than being rendered, while strip_tags() removes HTML and PHP tags entirely from a string.
PHP
#2.111
Q111:
What is the purpose of PHP's random_bytes() and random_int() functions?
Ans:
random_bytes() and random_int(), introduced in PHP 7, generate cryptographically secure random data suitable for security-sensitive tasks like tokens and keys, unlike rand() or mt_rand().
PHP
#2.112
Q112:
What is the principle of least privilege in the context of PHP applications?
Ans:
It means granting a database user or application component only the minimum permissions necessary to perform its function, limiting damage if that component is compromised.
PHP
#2.113
Q113:
Why should you disable display_errors in a production environment?
Ans:
Displaying detailed errors in production can expose sensitive information like file paths, database credentials, or code structure to attackers; errors should instead be logged and generic messages shown to users.
PHP
#2.114
Q114:
What is input validation versus input sanitization?
Ans:
Validation checks that input meets expected criteria (like a valid email format) and rejects it if not, while sanitization modifies or cleans the input to make it safe for use, such as stripping unwanted characters.
PHP
#2.115
Q115:
How do you use regular expressions in PHP?
Ans:
PHP uses PCRE (Perl Compatible Regular Expressions) functions like preg_match(), preg_match_all(), preg_replace(), and preg_split() to work with regex patterns.
Code Example
if (preg_match('/^[a-z]+$/', $str)) { echo 'matches'; }
PHP
#2.116
Q116:
What is the difference between preg_match() and preg_match_all()?
Ans:
preg_match() finds only the first match of a pattern in a string, while preg_match_all() finds all matches and returns them in an array.
PHP
#2.117
Q117:
How do you replace text using a regular expression?
Ans:
preg_replace() searches a string for a pattern match and replaces it with a replacement string, supporting backreferences to captured groups.
Code Example
echo preg_replace('/\d+/', '#', 'Order 123 shipped'); // 'Order # shipped'
PHP
#2.118
Q118:
How do you split a string using a regular expression?
Ans:
preg_split() splits a string into an array using a regular expression as the delimiter, offering more flexibility than explode().
Code Example
print_r(preg_split('/[\s,]+/', 'a, b c'));
PHP
#2.119
Q119:
What are capturing groups in regex?
Ans:
Capturing groups, defined with parentheses (), allow you to extract specific portions of a matched pattern for later use or reference.
Code Example
preg_match('/(\d{3})-(\d{4})/', '555-1234', $matches);
// $matches[1] = '555', $matches[2] = '1234'
PHP
#2.120
Q120:
What is the DateTime class used for?
Ans:
DateTime is an object-oriented way to represent, manipulate, and format dates and times, offering more functionality than the procedural date() function.
Code Example
$date = new DateTime('2024-01-15');
echo $date->format('d/m/Y');
PHP
#2.121
Q121:
How do you calculate the difference between two dates?
Ans:
You can use the diff() method on two DateTime objects, which returns a DateInterval object describing the difference in years, months, days, etc.
Code Example
$d1 = new DateTime('2024-01-01');
$d2 = new DateTime('2024-03-15');
$diff = $d1->diff($d2);
echo $diff->days;
PHP
#2.122
Q122:
How do you add or subtract time from a date?
Ans:
You can use the modify() method with a relative format string, or the add()/sub() methods with a DateInterval object.
Code Example
$date = new DateTime('2024-01-01');
$date->modify('+1 month');
PHP
#2.123
Q123:
How do you handle time zones in PHP?
Ans:
You can set the default timezone with date_default_timezone_set(), or specify a DateTimeZone object when creating DateTime instances to work with specific zones.
Code Example
$date = new DateTime('now', new DateTimeZone('America/New_York'));
PHP
#2.124
Q124:
What problem do namespaces solve in PHP?
Ans:
Namespaces prevent naming collisions between classes, functions, and constants from different libraries or parts of an application that might otherwise share the same name.
PHP
#2.125
Q125:
How do you import a namespaced class for use in your code?
Ans:
You use the 'use' keyword to import a fully qualified class name, optionally with an alias, so it can be referenced by its short name.
Code Example
use App\Models\User as UserModel;
PHP
#2.126
Q126:
What is autoloading in PHP and how does Composer handle it?
Ans:
Autoloading automatically loads class files when needed instead of manually requiring each one; Composer generates an autoloader (often PSR-4 based) that maps namespaces to directory structures.
Code Example
require 'vendor/autoload.php';
PHP
#2.127
Q127:
What is PSR-4 in the context of PHP?
Ans:
PSR-4 is a PHP-FIG standard defining how namespaces and class names should map to file paths for autoloading purposes.
PHP
#2.128
Q128:
What are union types in PHP 8?
Ans:
Union types allow a parameter, return value, or property to accept more than one specified type, separated by a pipe (|).
Code Example
function process(int|string $id): void {}
PHP
#2.129
Q129:
What is the mixed type in PHP 8?
Ans:
mixed is a pseudo-type indicating a parameter or return value can be of any type, equivalent to having no type restriction while still being explicit.
PHP
#2.130
Q130:
What is the nullsafe operator in PHP 8?
Ans:
The nullsafe operator (?->) allows chaining method or property access on a potentially null object, short-circuiting to null instead of throwing an error if any part of the chain is null.
Code Example
$country = $user?->getAddress()?->getCountry();
PHP
#2.131
Q131:
What is opcode caching and why does it matter for PHP performance?
Ans:
Opcode caching (like OPcache) stores precompiled script bytecode in memory, avoiding the need to parse and compile PHP files on every request, significantly improving performance.
PHP
#2.132
Q132:
What is the difference between require_once and a namespace-based autoloader?
Ans:
require_once manually and explicitly loads a specific file each time it's needed, while an autoloader automatically loads class files on demand based on naming conventions, reducing manual include statements.
PHP
#2.133
Q133:
What is the difference between static and instance methods regarding $this?
Ans:
Instance methods have access to $this referring to the current object, while static methods do not have an object context and cannot use $this.
PHP
#2.134
Q134:
What is object destructuring with list() and named keys?
Ans:
PHP 7.1+ allows list() and short array syntax to destructure associative arrays using key => variable pairs, extracting values into variables by key rather than position.
Code Example
['name' => $name, 'age' => $age] = $user;
PHP
#2.135
Q135:
What is the difference between == null and === null checks?
Ans:
== null is true for many falsy values in older PHP behavior contexts depending on type juggling rules, while === null strictly checks that the value's type is exactly NULL; using is_null() or === null is safer and clearer.
PHP
#2.136
Q136:
How do you check the number of days in a given month using PHP?
Ans:
You can use cal_days_in_month() or format a DateTime object with 't' to get the number of days in that month.
Code Example
echo date('t', strtotime('2024-02-01')); // 29
PHP
#2.137
Q137:
What is the difference between require and autoloading for including classes?
Ans:
require directly and immediately loads a specified file regardless of whether the class is used, while autoloading defers loading until the class is actually referenced, improving efficiency in large codebases.
PHP
#2.138
Q138:
How do you check whether a class implements a specific interface?
Ans:
You can use the instanceof operator on an object, or class_implements() to get an array of interfaces implemented by a class.
Code Example
print_r(class_implements('Circle'));
PHP
#2.139
Q139:
What is the difference between array_key_first() and array_key_last()?
Ans:
array_key_first() returns the key of the first element in an array, and array_key_last() returns the key of the last element, both without modifying the array's internal pointer.
PHP
#2.140
Q140:
How do you compare two arrays for equality in PHP?
Ans:
Using == checks if arrays have the same key-value pairs regardless of order, while === checks that they have the same key-value pairs in the same order and same types.
PHP
#2.141
Q141:
What is the difference between compact() and extract()?
Ans:
compact() creates an array from variable names and their values, while extract() does the reverse, importing array keys into variables in the current scope.
Code Example
$name='Tom'; $age=25;
$data = compact('name', 'age'); // ['name'=>'Tom','age'=>25]
extract($data);
PHP
#2.142
Q142:
What is the purpose of the __LINE__, __FILE__, and __FUNCTION__ magic constants?
Ans:
These are predefined constants that resolve to the current line number, current file path, and current function name respectively, useful for debugging and logging.
PHP
#2.143
Q143:
What does the array_diff() function do?
Ans:
array_diff() returns the values in the first array that are not present in any of the other given arrays, comparing values as strings.
Code Example
print_r(array_diff([1,2,3], [2,3])); // [0 => 1]
PHP
#2.144
Q144:
What does the array_intersect() function do?
Ans:
array_intersect() returns the values that are present in all of the given arrays, preserving the keys from the first array.
Code Example
print_r(array_intersect([1,2,3], [2,3,4])); // [1=>2, 2=>3]
PHP
#2.145
Q145:
What is the difference between require and require_once regarding performance?
Ans:
require_once has slightly more overhead because it checks a list of already-included files before including, while require always includes the file; for files that should load once (like class definitions), require_once prevents redeclaration errors.
PHP
#2.146
Q146:
What is method chaining and how do you implement it?
Ans:
Method chaining allows calling multiple methods sequentially on the same object in one statement by having each method return $this.
Code Example
class Query {
function where($cond){ $this->conditions[]=$cond; return $this; }
function orderBy($col){ $this->order=$col; return $this; }
}
$q = (new Query())->where('age > 18')->orderBy('name');
Hard
38 questions
PHP
#3.1
Q1:
Why should you unset the reference variable after a foreach loop by reference?
Ans:
Because the reference variable continues to point to the last array element after the loop, so subsequent reuse of that variable name can unintentionally overwrite array data.
PHP
#3.2
Q2:
What is the difference between func_get_args() and variadic parameters?
Ans:
func_get_args() retrieves all arguments passed to a function regardless of the declared parameter list, while variadic parameters (...) explicitly collect extra arguments into a named array within the signature.
PHP
#3.3
Q3:
What is a first-class callable syntax in PHP 8.1?
Ans:
PHP 8.1 introduced a shorthand (strlen(...)) to create a Closure from any callable without using Closure::fromCallable() or a string reference.
Code Example
$fn = strlen(...);
PHP
#3.4
Q4:
How do you flatten a multidimensional array?
Ans:
There's no single built-in flatten function; you typically use array_merge(...$array) with the spread operator, or a recursive function combined with array_walk_recursive().
PHP
#3.5
Q5:
How do you iterate over an array and modify keys?
Ans:
You can build a new array using array_map with ARRAY_FILTER_USE_KEY, or manually loop and reassign, since PHP has no direct 'map keys' function.
PHP
#3.6
Q6:
Does PHP support method overloading like some other languages?
Ans:
PHP does not support traditional method overloading (same method name, different signatures); instead it uses magic methods like __call() to simulate dynamic method handling.
PHP
#3.7
Q7:
How do you resolve method conflicts between multiple traits?
Ans:
You use the 'insteadof' operator to specify which trait's method takes precedence, and 'as' to create an alias for a conflicting method.
Code Example
class C { use A, B { A::hello insteadof B; B::hello as helloB; } }
PHP
#3.8
Q8:
What is the difference between self:: and static:: in PHP?
Ans:
self:: refers to the class where the code is defined (compile-time binding), while static:: uses late static binding, resolving to the actual called class at runtime.
PHP
#3.9
Q9:
What is late static binding?
Ans:
Late static binding, introduced in PHP 5.3, allows referencing the called class in a context of static inheritance using the static:: keyword instead of self::.
PHP
#3.10
Q10:
What is __get() and __set() used for?
Ans:
__get() and __set() are magic methods triggered when accessing or assigning inaccessible or non-existent properties, enabling dynamic property handling.
Code Example
class Bag {
private array $data = [];
function __get($name){ return $this->data[$name] ?? null; }
function __set($name, $value){ $this->data[$name] = $value; }
}
PHP
#3.11
Q11:
What is __call() and __callStatic() used for?
Ans:
__call() is invoked when calling inaccessible or undefined instance methods, and __callStatic() does the same for static method calls, both useful for dynamic method dispatch.
PHP
#3.12
Q12:
What is __invoke() used for?
Ans:
__invoke() allows an object to be called as if it were a function.
Code Example
class Adder {
function __invoke($a, $b) { return $a + $b; }
}
$add = new Adder();
echo $add(2,3); // 5
PHP
#3.13
Q13:
What is __clone() used for?
Ans:
__clone() is automatically called when an object is cloned with the clone keyword, useful for deep-copying nested objects.
Code Example
$copy = clone $original;
PHP
#3.14
Q14:
What is an anonymous class in PHP?
Ans:
Introduced in PHP 7, anonymous classes let you create an object with a class definition inline, without naming the class, useful for simple one-off objects.
Code Example
$obj = new class {
public function hello() { return 'hi'; }
};
PHP
#3.15
Q15:
What is the Throwable interface?
Ans:
Throwable is the base interface implemented by both the Error and Exception class hierarchies, allowing a single catch block to handle either type.
PHP
#3.16
Q16:
What is a custom error handler in PHP?
Ans:
set_error_handler() registers a user-defined function to handle PHP errors instead of the default handler, allowing custom logging or formatting.
Code Example
set_error_handler(function($errno, $errstr) {
echo "Error: $errstr";
});
PHP
#3.17
Q17:
What is set_exception_handler() used for?
Ans:
set_exception_handler() defines a global function to handle any uncaught exceptions in the script, useful as a last resort for logging fatal issues.
PHP
#3.18
Q18:
What security checks should you perform on file uploads?
Ans:
You should validate file type and extension, check MIME type, enforce file size limits, rename files to avoid path traversal, and store uploads outside the web root or with restricted execution permissions.
PHP
#3.19
Q19:
What is session hijacking and how can it be mitigated?
Ans:
Session hijacking is when an attacker steals a valid session ID to impersonate a user; mitigations include regenerating the session ID after login with session_regenerate_id(), using HTTPS, and setting HttpOnly/Secure cookie flags.
PHP
#3.20
Q20:
What is a CSRF token and how is it typically implemented?
Ans:
A CSRF token is a random, unique value generated per session or form, embedded as a hidden field, and verified against the stored value on submission to ensure the request originated from the legitimate site.
Code Example
$_SESSION['csrf'] = bin2hex(random_bytes(32));
// in form:
<input type='hidden' name='csrf' value='<?= $_SESSION['csrf'] ?>'>
PHP
#3.21
Q21:
How do you prevent directory traversal attacks in PHP file operations?
Ans:
You should validate and sanitize file paths, use realpath() to resolve and confirm paths stay within an allowed directory, and avoid directly using user input to build file paths.
PHP
#3.22
Q22:
How do you validate an email format using regex versus filter_var?
Ans:
While regex patterns can validate email format, filter_var() with FILTER_VALIDATE_EMAIL is generally preferred since it is built-in, well-tested, and handles edge cases more reliably than most custom regex.
PHP
#3.23
Q23:
What is a non-greedy quantifier in regex?
Ans:
A non-greedy (lazy) quantifier, denoted by adding a ? after * or +, matches as few characters as possible instead of the default greedy behavior of matching as many as possible.
Code Example
preg_match('/<.+?>/', '<a><b>', $m); // matches '<a>' not '<a><b>'
PHP
#3.24
Q24:
What are attributes in PHP 8?
Ans:
Attributes provide a structured, native way to add metadata to classes, methods, and properties using #[...] syntax, replacing many use cases previously handled by docblock annotations.
Code Example
#[Route('/users', methods: ['GET'])]
function listUsers() {}
PHP
#3.25
Q25:
What is the JIT compiler introduced in PHP 8?
Ans:
The Just-In-Time compiler translates parts of the code into machine code at runtime, which can improve performance for CPU-intensive tasks, though typical web request performance gains are often modest.
PHP
#3.26
Q26:
What are the differences in error handling for division by zero between PHP 7 and PHP 8?
Ans:
In PHP 8, dividing an integer or float by zero using the / operator throws a DivisionByZeroError, whereas in PHP 7 it produced a warning and returned INF or NAN.
PHP
#3.27
Q27:
How has string-to-number comparison changed in PHP 8?
Ans:
In PHP 8, when comparing a number to a non-numeric string, the number is converted to a string for comparison (rather than the string being converted to 0 as in PHP 7), making comparisons more intuitive.
PHP
#3.28
Q28:
What is the WeakMap class introduced in PHP 8?
Ans:
WeakMap allows objects to be used as keys without preventing those objects from being garbage collected, useful for caching metadata about objects without causing memory leaks.
PHP
#3.29
Q29:
What are traits' limitations compared to interfaces?
Ans:
Traits provide actual method implementations for code reuse but do not enforce a contract or support polymorphism through type checking the way interfaces do; a class using a trait isn't considered an instance of that trait via instanceof.
PHP
#3.30
Q30:
What is Composer's autoload-dev section used for?
Ans:
autoload-dev defines autoloading rules that apply only during development, such as loading test classes, and are excluded when the package is installed as a dependency in production.
PHP
#3.31
Q31:
What is a PHP interface constant and can it be overridden?
Ans:
Interfaces can declare constants that implementing classes inherit; as of PHP 8.1, interface constants can be effectively customized via enum-based interfaces, but classic interface constants cannot be changed by implementing classes, only used.
PHP
#3.32
Q32:
What does the yield keyword do in PHP?
Ans:
yield is used inside a generator function to return a value to the caller while pausing execution, allowing iteration over potentially large or infinite sequences without holding all values in memory at once.
Code Example
function numbers() {
for ($i = 1; $i <= 3; $i++) {
yield $i;
}
}
foreach (numbers() as $n) { echo $n; }
PHP
#3.33
Q33:
What is a PHP generator?
Ans:
A generator is a special type of iterator defined using a function containing yield statements, producing values one at a time on demand rather than computing and storing them all at once.
PHP
#3.34
Q34:
What is the difference between a generator and a regular array-returning function?
Ans:
A generator produces values lazily one at a time as they're requested, using minimal memory even for large datasets, while a regular function that returns an array must build and hold the entire result set in memory at once.
PHP
#3.35
Q35:
What is the __autoload function and why is it deprecated?
Ans:
__autoload() was a magic function used before PSR-based autoloaders to automatically load classes, but it was deprecated and removed in favor of the more flexible spl_autoload_register() function.
PHP
#3.36
Q36:
What does spl_autoload_register() do?
Ans:
spl_autoload_register() registers a function to be called automatically whenever an undefined class is referenced, forming the foundation for modern autoloading systems.
Code Example
spl_autoload_register(function ($class) {
include 'classes/' . $class . '.php';
});
PHP
#3.37
Q37:
What is the difference between abstract methods and interface methods in terms of visibility?
Ans:
Abstract methods can be declared as public or protected, while interface methods are implicitly and must be public since interfaces define a public contract.
PHP
#3.38
Q38:
What is the difference between a shallow copy and deep copy of an array in PHP?
Ans:
PHP arrays are copied by value by default (a shallow copy of scalar elements), but arrays containing objects only copy object references, so modifying a nested object still affects the original array's object.