PHP Developer interview questions
100 real questions with model answers and explanations for Junior PHP Developer candidates.
See a PHP Developer resume example →Practice with flashcards
Spaced repetition · Hunter Pass
Questions
PHP provides scalar, compound, and special value types.
- Scalar types include bool, int, float, and string.
- Compound types include array, object, callable, and iterable.
- null represents the absence of a value, while resource represents a handle to an external resource.
Why interviewers ask this: The interviewer checks whether you recognize the main categories of values handled by PHP code.
Dynamic typing means a variable's type is determined from its current value at runtime rather than fixed at declaration.
- The same variable can hold values of different types during its lifetime.
- PHP may coerce compatible scalar values in some operations and function calls.
- Parameter, property, and return declarations still let developers enforce explicit contracts.
Why interviewers ask this: A strong answer distinguishes PHP's runtime variable types from its optional declared type contracts.
It disables scalar argument coercion for function calls made from that file.
- Without strict mode, PHP may coerce a compatible scalar argument such as a numeric string to an int.
- With strict mode, an incompatible scalar argument normally causes a TypeError instead.
- It does not turn PHP into a statically typed language or validate untyped variables automatically.
Why interviewers ask this: The interviewer evaluates whether you understand the scope and limits of PHP strict types.
The == operator compares values after PHP type juggling, while === requires both value and type to match.
- A loose comparison can treat values of different types as equal after coercion.
- An identical comparison performs no type conversion.
- Strict comparison is usually safer when input may contain strings, numbers, booleans, or null.
Why interviewers ask this: The interviewer checks whether you understand how loose comparison can produce unexpected equality.
A cast converts a value to a requested type with syntax such as (int), (float), (string), (bool), or (array).
- Casting a numeric string to int or float produces its numeric value according to PHP conversion rules.
- Boolean casting follows PHP truthiness rules rather than parsing words such as false semantically.
- A cast does not validate whether the original value was meaningful for the application.
Why interviewers ask this: A strong answer separates mechanical conversion from business-level input validation.
PHP supports type declarations on function parameters, return values, and class properties.
- Declarations document the values that an API accepts, returns, or stores.
- Violations produce TypeError rather than silently storing an incompatible value.
- Built-in types, class names, interfaces, and compound types can participate in declarations.
Why interviewers ask this: The interviewer checks whether you know how PHP expresses contracts across functions and classes.
A nullable type permits null, while a union type permits a value from several listed types.
- ?User is shorthand for User|null.
- A declaration such as int|float accepts either listed numeric type.
- Union members should describe a meaningful contract rather than replace clear data modeling with many alternatives.
Why interviewers ask this: A strong answer explains both the syntax and the purpose of compound type declarations.
PHP treats false, 0, 0.0, empty strings, the string '0', an empty array, and null as falsey.
- Other non-empty strings are truthy even when their text reads 'false'.
- Empty objects are truthy.
- Explicit comparison is clearer when zero, an empty string, and null have different meanings.
Why interviewers ask this: The interviewer evaluates whether you know the falsey values that affect conditions and input checks.
The ?? operator returns its left operand when that value is set and not null, otherwise it returns the right operand.
- It is commonly used for optional array keys or request values.
- Its check follows isset semantics, so a present key containing null uses the fallback.
- It avoids the undefined-key notice that direct access could produce before a fallback.
Why interviewers ask this: The interviewer checks whether you understand both the fallback behavior and its treatment of null.
Single-quoted strings perform minimal escaping, while double-quoted strings interpret variables and more escape sequences.
- A double-quoted string can interpolate a variable such as $name.
- The dot operator concatenates strings regardless of quote style.
- Braces make interpolation boundaries clear when a variable touches surrounding text.
Why interviewers ask this: The interviewer checks whether you understand PHP string literals, interpolation, and concatenation.
strlen returns the number of bytes in a string, while mb_strlen counts characters for a specified multibyte encoding.
- ASCII characters usually occupy one byte, so both results often match for ASCII text.
- UTF-8 characters may occupy several bytes, making strlen unsuitable for a character count.
- mb_strlen requires the mbstring extension and should use the application's known encoding.
Why interviewers ask this: A strong answer recognizes that PHP strings are byte sequences and that user-facing text may be multibyte.
str_contains and strpos search within strings, while substr extracts a portion by offset and length.
- str_contains returns a boolean and is convenient for a simple containment check.
- strpos returns an integer position or false, so position zero must be compared with !== false.
- Multibyte text may require the corresponding mb_ functions for character-based offsets.
Why interviewers ask this: The interviewer checks whether you know common string APIs and the important strpos return-value detail.
An indexed array uses integer keys, while an associative array uses string keys to name values.
- PHP implements both forms with the same ordered array type.
- Integer and string keys can coexist in one array, although a consistent shape is easier to maintain.
- Indexed arrays commonly represent lists, while associative arrays commonly represent records or lookup tables.
Why interviewers ask this: A strong answer understands that PHP arrays cover both list-like and map-like structures.
PHP uses square-bracket syntax for array access and assignment, with [] appending to the next integer key.
- $items['name'] reads or writes a named key.
- $items[] = $value appends without manually calculating an index.
- unset($items[$key]) removes a key without automatically reindexing the remaining integer keys.
Why interviewers ask this: The interviewer checks whether you know the basic operations and key behavior of PHP arrays.
isset checks that a key exists and its value is not null, while array_key_exists checks only whether the key exists.
- A key with a null value makes isset return false.
- The same key makes array_key_exists return true.
- The choice depends on whether null means missing or is a valid stored value.
Why interviewers ask this: A strong answer explains the semantic difference for keys whose value is null.
They transform, select, and aggregate array values through callback functions.
- array_map produces values by applying a callback to input elements.
- array_filter keeps elements that satisfy a callback and preserves their original keys.
- array_reduce combines all elements into one accumulated result.
Why interviewers ask this: The interviewer checks whether you can distinguish the three core array-processing operations.
sort orders values and reindexes keys, asort orders values while preserving key associations, and ksort orders by keys.
- sort is suitable for a simple indexed list where original keys do not matter.
- asort keeps each value paired with its existing key.
- The functions mutate the supplied array and return a success boolean rather than the sorted array.
Why interviewers ask this: A strong answer chooses a sorting function according to whether keys carry meaning.
They all combine arrays, but their behavior for duplicate and numeric keys differs.
- array_merge overwrites duplicate string keys with later values and reindexes numeric keys.
- Array unpacking with ... is convenient for building a new array and generally follows merge-like numeric-key behavior.
- The + operator preserves values from the left array when the same key exists on both sides.
Why interviewers ask this: The interviewer evaluates whether you know that PHP array-combination syntax has different key semantics.
Array destructuring assigns array elements to separate variables with [] or list syntax.
- Positional destructuring reads values by integer position.
- Associative destructuring can name the keys being extracted.
- Missing elements may produce warnings, so the expected array shape should be known.
Why interviewers ask this: The interviewer checks whether you recognize concise extraction from known array shapes.
foreach iterates an array by value by default and can bind the loop variable by reference with &.
- By-value iteration does not directly modify scalar elements through the loop variable.
- By-reference iteration can update the original elements.
- The reference variable should be unset after the loop so later assignments do not modify the last element accidentally.
Why interviewers ask this: A strong answer understands both normal foreach behavior and the persistent-reference hazard.
Locked questions
- 21
What parts form a PHP function signature?
formsphp - 22
How does variable scope work in PHP functions?
scopephp - 23
What is a closure in PHP, and how does use work?
closuresphp - 24
How do arrow functions differ from traditional anonymous functions in PHP?
functionsphp - 25
What is the difference between passing an argument by value and by reference in PHP?
php - 26
What are default, variadic, and named arguments in PHP?
php - 27
What is the difference between a class and an object in PHP?
oopphp - 28
What is constructor property promotion in PHP?
php - 29
What do public, protected, and private visibility mean in PHP?
cssphp - 30
How does class inheritance work in PHP?
oopphpownership - 31
What is an abstract class in PHP?
php - 32
What is an interface in PHP?
typesphp - 33
What is a trait in PHP?
traitsphp - 34
What are static properties and methods in PHP?
php - 35
What do $this, self, and parent refer to in PHP classes?
php - 36
What does the final keyword do in PHP OOP?
php - 37
What are magic methods in PHP?
magic-methodsphp - 38
What are namespaces and the use statement for in PHP?
namespacesphpkubernetes - 39
What is Composer used for in PHP projects?
composerphp - 40
What is the difference between composer.json and composer.lock?
composer - 41
How does PSR-4 autoloading map a class to a file?
psrautoloading - 42
How do include, require, include_once, and require_once differ?
- 43
What are PHP superglobals, and which ones are commonly used for web requests?
php - 44
How do PHP sessions work at a basic level?
sessionsphp - 45
What is a cookie, and what do its common security attributes do?
cookies - 46
What is the relationship between errors, exceptions, and Throwable in modern PHP?
error-handlingphp - 47
How do try, catch, finally, throw, and exception chaining work in PHP?
error-handlingphp - 48
What is PDO, and what are its basic connection and fetch concepts?
pdo - 49
What are PDO prepared statements, and why are they important?
pdo - 50
What is a database transaction in PDO?
databasetransactionspdo - 51
How would you count word frequencies in a PHP array while ignoring case and surrounding spaces?
php - 52
How would you group a list of product arrays by category ID?
- 53
How would you remove duplicate email addresses while preserving the first spelling and order?
- 54
How would you sort order records by total descending and creation date ascending for ties?
- 55
How would you safely read a city from a nested request array?
- 56
How would you collect all unique tags from products whose tags are stored as nested arrays?
- 57
How would you parse a CSV line that may contain commas inside quoted fields?
- 58
How would you truncate a UTF-8 title to 60 characters without cutting a multibyte character?
- 59
How would you replace {name} and {order_id} placeholders in a message template?
- 60
A role check accepts the integer 0 as equal to the string '0'. How would you make the check type-safe?
- 61
How would you write a typed function that calculates an order total from price and quantity lines?
- 62
How would you turn an associative request array into a typed registration object?
- 63
How would you split a large list of IDs into batches of 100 for processing?
batchconcurrency - 64
How would you validate a positive integer page parameter from $_GET?
validation - 65
How would you validate a required email field submitted by a form?
formsvalidation - 66
An unchecked checkbox is missing from $_POST. How would you process it correctly?
concurrency - 67
How would you redisplay submitted form values after validation fails without introducing XSS?
xssvalidationredis - 68
How would you add CSRF protection to a state-changing PHP form?
formscsrfphp - 69
How would you safely display a user-provided comment in an HTML page?
html - 70
How would you prevent a successful form submission from being repeated on browser refresh?
forms - 71
How would you read and validate a JSON request body in a PHP endpoint?
validationendpointsphp - 72
How would you store and verify user passwords in PHP?
passwordsphp - 73
PHP reports 'headers already sent' when setting a redirect or cookie. How would you fix it?
cookiesphp - 74
How would you ensure a form handler accepts only POST requests with expected fields?
forms - 75
A multiple-select field may submit one value, many values, or nothing. How would you normalize it?
normalization - 76
How would you fetch a user by ID with PDO without SQL injection?
sqlpdoinjection - 77
How would you insert a new product with named PDO placeholders?
pdo - 78
How would you implement a PDO search query using LIKE safely?
queriespdo - 79
How would you build a prepared PDO query for a dynamic list of IDs in an IN clause?
queriespdo - 80
How would you save an order and its line items atomically with PDO?
pdoconcurrency - 81
PDO fetch returns false and later array access raises a warning. How would you correct the code?
pdo - 82
How would you paginate a PDO product query without accepting arbitrary SQL fragments?
sqlqueriespdo - 83
How would you configure PDO so database errors are not silently ignored?
databasepdoconfig - 84
How would you prevent a PDO connection from exposing credentials in source control?
pdo - 85
How would you establish a session after a user logs in successfully?
sessions - 86
How would you implement logout for a PHP session?
sessionsphp - 87
How would you show a success message once after redirecting from a form submission?
forms - 88
How would you configure a session cookie for an HTTPS application?
sessionscookieshttps - 89
How would you store a user's language preference in a cookie?
cookies - 90
How would you handle PHP file-upload errors and enforce a size limit?
php - 91
How would you verify that an uploaded file is really an allowed image type?
- 92
How would you store an uploaded file without allowing path traversal or filename collisions?
- 93
A PDO transaction throws an exception halfway through. How would you handle it?
transactionspdoerror-handling - 94
How would you return a safe 500 response when an unexpected exception reaches a PHP endpoint?
error-handlingphpendpoints - 95
How would you validate a date in YYYY-MM-DD format without accepting PHP's automatic date corrections?
validationphp - 96
PHP reports an undefined array key from request data. How would you fix it?
fundamentalsphp - 97
PHP prints 'Array' and raises an array-to-string conversion warning. How would you diagnose it?
php - 98
Values change unexpectedly after a foreach loop that used references. How would you fix it?
- 99
Composer autoloading reports 'Class not found' for a project class. What would you check?
composerautoloading - 100
A PHP page is blank in production. How would you investigate it safely?
php