Menu

PHP Interview Questions and Answers (PHP 8)

24 PHP interview questions with short, correct answers for PHP 8, from == vs === and isset vs empty to references in foreach, self vs static, generators, SQL injection and password hashing. Most answers have code you can run and change.

This page includes runnable editors - edit, run, and see output instantly.

These are the PHP questions that come up most in interviews, with short answers that are correct for PHP 8.3 and code where code makes the point. Predict each block's output before you press Run: that is what an interviewer tests.

Beginner PHP interview questions

What is PHP and how does it run?

PHP is a server-side scripting language. A web server (Nginx or Apache) passes the request to PHP (usually PHP-FPM), PHP runs the script from the top, and whatever it prints becomes the response, usually HTML. Each request starts fresh: variables do not survive between requests unless you store them in a session, a database or a cache. PHP also runs scripts on the command line (php script.php).

What is the difference between == and ===?

== compares after type juggling, === compares value and type with no conversion. The warm-up above shows == at work: numeric strings are compared as numbers, so '10' == '1e1' is true. Since PHP 8, a number compared with a non-numeric string is compared as strings, so 0 == 'a' is false (in PHP 7 it was true). Tap the cells to compare both operators:

Loose (==) and strict (===) comparison
Point at or tap a cell to read it as PHP.
$a == $btruefalse01"0""1"""null[]"a""10""1e1"
true
false
0
1
"0"
"1"
""
null
[]
"a"
"10"
"1e1"
Every cell computed by PHP 8.3.19.

Use === by default. in_array() and array_search() use == unless you pass true as the third argument.

What is the difference between echo and print?

Both output strings. echo takes several arguments (echo $a, $b;) and returns nothing; print takes one and returns 1, so it can be used in an expression. Neither is a function, so parentheses are optional. In practice everyone uses echo.

Single quotes vs double quotes?

Double-quoted strings interpolate variables and escape sequences: "Hi $name\n". Single-quoted strings are literal except for \' and \\: 'Hi $name\n' prints exactly those characters. The speed difference is negligible, so the choice is about readability: double quotes when you interpolate, single quotes when you do not.

What are the data types in PHP?

Four scalar types (int, float, string, bool), two compound types (array and object), and two special ones (null and resource). callable, iterable, mixed and void exist only as type declarations, never as the type of a value. gettype() and get_debug_type() tell you a value's type at runtime, and var_dump() prints it with the value.

What is the difference between isset, empty and is_null?

isset($x) is true when the variable exists and is not null. empty($x) is true when the variable does not exist or is falsy (0, '0', '', [], false, null). is_null($x) is true for null, but warns on an undefined variable. isset and empty never warn, which is why they are used on array keys.

isset, empty and is_null for each value of $x
Point at or tap a cell to read it as PHP.
$xissetemptyis_null
null
false
0
"0"
""
" "
[]
"a"
0.0
Every cell computed by PHP 8.3.19.

The row people get wrong is "0": the string zero is empty, while " " (a space) is not. The isset page has the full table.

What is the difference between include and require?

Both insert and run another file. If the file is missing, include emits a warning and the script continues, while require throws an Error ("Failed opening required"), which stops the script unless something catches it. The _once variants (include_once, require_once) skip a file that was already loaded, which prevents "cannot redeclare function" errors. Use require (or require_once) for files the script cannot run without, which is almost all of them; Composer's autoloader makes most manual includes unnecessary.

What is the difference between GET and POST?

GET sends data in the URL's query string ($_GET), so it is visible, bookmarkable and limited in length; use it for reading, like search and pagination. POST sends data in the request body ($_POST); use it for anything that changes state, like login, saving or payments. A GET request should never change data, because links get prefetched and crawled.

What is the null coalescing operator?

$a ?? $b returns $a if it exists and is not null, otherwise $b, without a warning for an undefined variable or key: $page = $_GET['page'] ?? 1;. ??= assigns only when the left side is null or missing. It differs from ?:, which falls back on any falsy value, so 0 ?: 5 is 5 but 0 ?? 5 is 0.

Intermediate PHP interview questions

What happens when you loop by reference in foreach?

foreach ($arr as &$v) lets you modify elements in place, but $v stays a reference to the last element after the loop. Reusing the name in a second loop then overwrites that element:

The last element is 20, not 30: during the second loop, $v (still $arr[2]) is assigned 10, then 20, then itself. Remove the // before unset($v) and run it again. The foreach page covers references in detail.

What is the difference between an abstract class and an interface? And what is a trait?

An interface is a contract: method signatures (and constants) with no implementation, and a class can implement many. An abstract class can hold properties, constructors and finished methods, plus abstract methods its children must write; a class extends only one. A trait is a set of methods copied into a class with use, for reusing code across classes that do not share a parent.

A short answer interviewers like: use an interface to say what something can do, an abstract class to share how it is done, and a trait when unrelated classes need the same few methods.

What is the difference between self and static?

self refers to the class where the code is written. static refers to the class that was actually called at runtime, which is called late static binding. It matters in parent methods that create or describe "this kind of object":

User::createStatic() builds a User. User::createSelf() builds a Model, which breaks the static return type, so PHP throws a TypeError. That is why factory methods use new static().

What are magic methods?

Methods PHP calls for you, all starting with two underscores. The common ones: __construct() when an object is created, __destruct() when it is destroyed, __toString() when it is used as a string, __get() and __set() for inaccessible properties, __call() and __callStatic() for missing methods, __invoke() when the object is called like a function, and __clone() after clone.

What is the difference between array_merge() and the + operator?

array_merge() appends: numeric keys are renumbered and later string keys overwrite earlier ones. + is a union: it keeps the left array and only adds keys that are missing, so for a duplicate key the first value wins.

+ is the right tool for defaults: $options + ['timeout' => 30] keeps what the caller passed and fills in the rest.

What does declare(strict_types=1) do?

Without it, PHP converts scalar arguments to the declared parameter type when it can: passing "5" to an int parameter gives 5. With declare(strict_types=1); as the first statement of a file, calls made from that file must pass the exact type, otherwise a TypeError is thrown (an int passed to a float parameter is the one allowed widening).

Delete the declare line and run it again: the second call returns 10 instead of throwing.

A cookie is stored in the browser and sent with every request, so the visitor can read and change it. A session stores data on the server and only keeps a random id in a cookie (PHPSESSID). Put anything that must be trusted, like the logged-in user id, in $_SESSION; after login, call session_regenerate_id(true). The sessions and cookies page has the code.

How do you prevent SQL injection?

Never build SQL by concatenating input. Use prepared statements, so values are sent separately from the query:

<?php
$stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?');
$stmt->execute([$email]);
$user = $stmt->fetch();

Placeholders work for values only. Table names, column names and ASC/DESC must be checked against an allowlist before they go into the SQL. See PDO.

How do you prevent XSS?

Escape output, not input: wrap every value printed into HTML in htmlspecialchars($value, ENT_QUOTES, 'UTF-8'), or use a template engine that does it automatically (Twig, Blade). Inside <script>, use json_encode() with JSON_HEX_TAG. Add a Content-Security-Policy header as a second layer.

How should passwords be stored?

With password_hash($password, PASSWORD_DEFAULT) and checked with password_verify($password, $hash). They use bcrypt (or Argon2id) with a random salt stored inside the hash and a deliberate cost. md5() and sha1() are wrong for passwords because they are fast and unsalted. Use password_needs_rehash() at login to upgrade old hashes.

Advanced PHP interview questions

What are generators and when would you use one?

A function containing yield returns a Generator that produces values one at a time, only when asked. It lets you loop over a large or endless sequence without building an array in memory:

Typical uses are reading a large file line by line, streaming database rows, and lazy pipelines. Generators also support keys (yield $key => $value), delegation (yield from), and receiving values with send().

What are closures, and what does use do?

An anonymous function (function () { ... }) is a Closure object. It does not see outer variables unless you list them in use, which copies the value at the moment the closure is created; use (&$x) captures by reference instead. Arrow functions (fn ($x) => $x * $factor) capture outer variables automatically, by value, and contain a single expression.

What is the difference between abstract, final and readonly?

abstract marks a class that cannot be instantiated, or a method a child must implement. final forbids overriding a method or extending a class. readonly (PHP 8.1) makes a property writable only once, from inside the class, usually in the constructor; PHP 8.2 added readonly classes, where every property is readonly.

What is Composer, and what is PSR-4?

Composer is PHP's dependency manager: composer.json lists the packages, composer.lock pins exact versions, and vendor/autoload.php loads everything. PSR-4 is the autoloading standard that maps a namespace prefix to a folder, so App\Mail\Mailer lives in src/Mail/Mailer.php and is loaded on first use. Explain install (from the lock file) vs update (new versions, new lock file).

What changed in PHP 8?

The headline features: in 8.0, named arguments, match, the nullsafe operator ?->, union types, constructor property promotion, attributes, str_contains(), and saner string-to-number comparison; in 8.1, enums, readonly properties, first-class callable syntax (strlen(...)) and fibers; in 8.2, readonly classes and standalone null/true/false types; in 8.3, typed class constants, the #[\Override] attribute and json_validate(); in 8.4, property hooks, asymmetric visibility (public private(set)), array_find() and new Foo()->method() without wrapping parentheses. Many functions also throw TypeError or ValueError now instead of returning false with a warning.

How does PHP manage memory?

Every value has a reference count; when it drops to zero, the memory is freed immediately. Objects that reference each other in a cycle never reach zero, so a cycle collector runs whenever its buffer of possible cycle roots fills up (10,000 entries by default) and frees them (gc_collect_cycles() runs it on demand). Arrays and strings are copy-on-write: assigning $b = $a shares the data until one of them is modified. Because each request starts and ends cleanly, memory leaks matter mostly in long-running workers and queue consumers.

How are PHP arrays implemented?

A PHP array is an ordered hash map: it keeps insertion order and maps int or string keys to values, which is why the same type serves as a list, a dictionary and a stack. Key lookups (isset($arr[$key])) take constant time on average, while in_array() scans every value. Integer-like string keys are converted: $a['1'] and $a[1] are the same element.

Common interview coding tasks

Short exercises often asked live. Each function is one common answer; run them, add your own inputs (including an empty one), and be ready to explain the time complexity, which is usually what the interviewer is checking.

Frequently Asked Questions

How do I prepare for a PHP developer interview?

Make sure you can explain and write code for the basics without looking them up: comparison and types, arrays and their functions, OOP (interfaces, abstract classes, traits, static), exceptions, and security (prepared statements, htmlspecialchars, password_hash). Then know one framework (Laravel or Symfony) and Composer well enough to talk through a project you built.

Which PHP version should I know for an interview?

PHP 8. Interviewers expect you to know features added in 8.0 to 8.3: named arguments, match, the nullsafe operator ?->, union types, constructor property promotion, enums, readonly properties and first-class callable syntax. Mention PHP 7 behavior only where it changed, such as 0 == "a".

What PHP questions are asked for freshers?

Mostly the language basics: == vs ===, echo vs print, single vs double quotes, isset vs empty, include vs require, GET vs POST, sessions vs cookies, and simple array tasks like reversing, filtering or counting values. Expect at least one short coding exercise.

What PHP questions are asked for experienced developers?

Design and behavior under the hood: interfaces vs abstract classes, traits, late static binding, references, generators and memory, exceptions and error handling, SQL injection and transactions, caching, Composer autoloading, and how you would structure or test a feature. Answers are expected to come with trade-offs, not definitions.

Coddy programming languages illustration

Learn to code with Coddy

GET STARTED