PHP Interview Questions and Answers: From Basics to PHP 8.5
If you’re preparing for PHP interview questions, the old trivia (single versus double quotes, == versus ===) still shows up in screening rounds, but most interviews now go further.
Expect modern language features, object-oriented design, security, database access, performance, and a scenario or two about messy real-world code.
One hiring guide notes that pure-recall questions no longer screen candidates well, because anyone can look up the answer, so interviewers lean on judgment: how you’d refactor a legacy app, or when you’d skip a full framework.
What’s current in 2026
Know which versions are supported before you walk in.
- PHP 8.5 was released on November 20, 2025. It adds the pipe operator (|>), a new URI extension, “clone with,” and the #[\NoDiscard] attribute, plus array_first() and array_last().
- PHP 8.4 (released November 21, 2024) introduced property hooks and asymmetric visibility.
- By one end-of-life tracker, PHP 8.5 gets active support until December 31, 2027 and security fixes until December 31, 2029. PHP 8.4’s active support ends December 31, 2026, PHP 8.2 reaches end of life on December 31, 2026, and PHP 8.1 reached end of life on December 31, 2025.
- Zend’s overview mentions PHP 8.6 is planned for later in 2026, so a newer release may land soon.
If a company runs 8.1 or older, expect interview questions about upgrading, since those versions no longer get security patches.
Basic PHP questions
1. What is PHP?
A server-side scripting language built for the web. It’s embedded in HTML or run from the command line, supports procedural and object-oriented styles, and powers platforms like WordPress and frameworks like Laravel and Symfony.
2. Is PHP compiled or interpreted?
Both, in a sense. The engine compiles source to opcodes (an intermediate form) and then executes them. OPcache stores those compiled opcodes so PHP doesn’t recompile on every request.
3. What’s the difference between == and ===?
== compares values after type juggling, and === compares value and type. PHP 8 changed some comparisons: 0 == “abc” was true in PHP 7 and is false in PHP 8.
var_dump(0 == “abc”); // false in PHP 8 (true in PHP 7)
var_dump(“1” == “01”); // true (both numeric strings)
var_dump(“10” == “1e1”); // true (numeric strings)
var_dump(100 == “1e2”); // true
var_dump(“abc” === “abc”); // true
4. What’s the difference between echo and print?
Both output strings. echo is a language construct that can take several arguments and returns nothing. print takes one argument and returns 1. In practice, use echo.
5. include vs require vs include_once?
require triggers a fatal error if the file is missing, while include raises a warning and continues. The _once versions skip files already loaded.
6. What are superglobals?
Built-in arrays available everywhere: $_GET, $_POST, $_SERVER, $_COOKIE, $_SESSION, $_FILES, $_ENV, and $_REQUEST. Never trust their contents without validation.
7. isset() vs empty() vs is_null()?
isset() is true if a variable exists and isn’t null. empty() is true for falsy values (0, “”, “0”, [], null, false). is_null() checks only for null and warns on undefined variables.
8. What are the null coalescing and spaceship operators?
?? returns the left side if it exists and isn’t null, otherwise the right ($name = $_GET[‘name’] ?? ‘guest’;). <=> returns -1, 0, or 1 and is handy in sorting callbacks.
9. What’s the difference between sessions and cookies?
Cookies are stored in the browser and sent with every request. Sessions store data on the server, with only a session ID in a cookie. Keep sensitive data in sessions, and regenerate the ID on login.
10. GET vs POST?
GET requests retrieve data and appear in the URL, so they suit searches and filters. POST sends data in the body for creating or changing things. Neither is secure by itself, so use HTTPS.
Types, functions, and arrays
11. What does declare(strict_types=1) do?
It enforces strict scalar type checks for function calls in that file, so passing “5” to an int parameter throws a TypeError instead of silently converting.
12. Name the scalar and compound types.
int, float, string, bool, array, object, callable, iterable, null, plus union types (int|string), nullable types (?string), and never and void for return types.
13. How are objects passed to functions?
An object variable holds a handle. A function receives a copy of that handle, so changes to the object’s properties are visible to the caller. But reassigning the parameter to a new object doesn’t affect the caller’s variable. Use & for true pass-by-reference.
14. Closures vs arrow functions?
Closures (function () use ($x) { … }) capture variables explicitly. Arrow functions (fn($n) => $n * $factor) capture the surrounding scope by value automatically and hold a single expression.
15. What are generators, and why use them?
A function using yield produces values lazily, so memory use stays flat for large datasets:
function readLines(string $file): Generator {
handle=fopen(file, ‘r’);
while ((line=fgets(handle)) !== false) {
yield rtrim($line, “\n”);
}
fclose($handle);
}
foreach (readLines(‘huge.csv’) as $line) { /* process one line at a time */ }
16. Which array functions should you know?
array_map, array_filter, array_reduce, array_merge, array_column, array_unique, usort, and in_array. PHP 8.4 added array_find() and related helpers, and 8.5 added array_first() and array_last().
Object-oriented PHP
17. Abstract class vs interface?
An abstract class can hold state and partial implementation, and a class extends only one. An interface declares only a contract, and a class can implement many.
18. What are traits?
A way to reuse methods across unrelated classes without multiple inheritance. Watch for naming conflicts, which you resolve with insteadof and as.
19. What are the visibility levels?
public, protected, and private. PHP 8.4 added asymmetric visibility, such as public private(set), so a property can be readable publicly but writable only inside the class.
20. self vs static, and what is late static binding?
self refers to the class where the code is written. static refers to the class that was actually called at runtime, which matters for inheritance and factory methods.
21. Name some magic methods.
__construct, __destruct, __get, __set, __call, __callStatic, __toString, and __invoke. Use them sparingly, since they hurt readability and static analysis.
22. What are namespaces and autoloading?
Namespaces prevent name collisions, and autoloading loads class files on demand. The standard approach is Composer with PSR-4, so a class App\Service\Mailer maps to src/Service/Mailer.php.
23. Show a modern class using enums, readonly, and constructor promotion.
enum Status: string {
case Draft = ‘draft’;
case Published = ‘published’;
}
final class Post {
public function __construct(
public readonly int $id,
public readonly string $title,
public readonly Status $status = Status::Draft,
) {}
}
24. What are property hooks (PHP 8.4)?
Getter and setter logic declared directly on the property, so you don’t need boilerplate methods:
class User {
public string $name {
set => ucfirst(trim($value));
}
}
Features by version
A quick table helps you answer “what’s new in PHP 8.x?” confidently:
| Version | Notable features |
| 8.0 | Named arguments, attributes, constructor promotion, match, nullsafe operator, union types, JIT |
| 8.1 | Enums, readonly properties, fibers, first-class callable syntax, never type |
| 8.2 | Readonly classes, DNF types, standalone null, true, and false types |
| 8.3 | Typed class constants, #[\Override], json_validate() |
| 8.4 | Property hooks, asymmetric visibility, new array functions |
| 8.5 | Pipe operator, URI extension, clone with, #[\NoDiscard], array_first() and array_last() |
The PHP 8.5 pipe operator reads left to right and uses first-class callables:
$slug = ‘ PHP 8.5 Released ‘
|> trim(…)
|> strtolower(…)
|> (fn (string $s) => str_replace(‘ ‘, ‘-‘, $s));
Security questions
25. How do you prevent SQL injection?
Use prepared statements with bound parameters, never string concatenation:
pdo=newPDO(dsn, $user, $pass, [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]);
$stmt = $pdo->prepare(‘SELECT id, email FROM users WHERE email = :email’);
$stmt->execute([’email’ => $email]);
$user = $stmt->fetch(PDO::FETCH_ASSOC);
26. How do you prevent XSS?
Escape output for its context. For HTML: htmlspecialchars($input, ENT_QUOTES, ‘UTF-8’). Templating engines like Twig and Blade escape by default.
27. How should you store passwords?
Use password_hash() and password_verify(), never MD5 or SHA-1. Use password_needs_rehash() to upgrade hashes over time.
28. What is CSRF, and how do you stop it?
An attack that tricks a logged-in user’s browser into sending an unwanted request. Defend with per-session tokens in forms, same-site cookies, and checking the request method and origin.
29. How do you handle file uploads safely?
Validate size and MIME type on the server, don’t trust the client filename, generate your own names, store files outside the web root (or on a private disk), and never execute uploaded files.
30. What are other common security basics?
Use HTTPS, regenerate session IDs on login, set secure cookie flags, keep dependencies updated (composer audit), disable error display in production, and use random_bytes() for tokens.
Database and error handling
31. PDO or mysqli?
PDO supports many databases through one API and has named parameters. mysqli is MySQL-specific. Most modern code uses PDO.
32. How do transactions work in PDO?
Call beginTransaction(), run your statements, then commit(), and rollBack() in a catch block if something fails.
33. What’s the difference between Error and Exception?
Both implement Throwable. Exception covers application-level problems, and Error covers engine-level ones like TypeError and DivisionByZeroError. Catch Throwable only at boundaries.
34. How do you handle errors in production?
Turn off display_errors, log errors to a file or monitoring service, use exception handlers, and return friendly messages to users.
Performance and architecture
35. How do you speed up a PHP app?
Enable OPcache, upgrade to a current PHP version, fix slow and N+1 queries, add indexes, cache results (APCu, Redis), move slow work to queues, use generators for big data, and profile with Xdebug or Blackfire before guessing.
36. What is PHP-FPM?
FastCGI Process Manager. It keeps a pool of PHP workers behind Nginx or Apache, and tuning the pool size affects memory and concurrency.
37. What are PSR standards?
Community standards from PHP-FIG: PSR-1 and PSR-12 (coding style), PSR-4 (autoloading), PSR-3 (logging), PSR-7 (HTTP messages), PSR-11 (containers), and PSR-15 (middleware).
38. Should every project use a framework?
No. For a small service, plain PHP plus a few good libraries can be the right call, and a full framework can be overkill. Hiring guides flag this as a senior-level judgment question.
Scenario questions
39. You inherit a legacy app with fat controllers and logic in the templates. Where do you start?
Add tests around critical paths first, upgrade PHP and dependencies, fix security issues, then refactor incrementally, extracting logic into services without a rewrite. Weigh risk against value and avoid burning it all down.
40. A page feels slow, but server metrics look healthy. What do you check?
Real user timings, database query counts, N+1 loads, cache hit rates, external API calls, frontend weight, and differences between test and production data.
41. How do you import a 1 GB CSV without timing out?
Process it in a queue or CLI job, read lines with a generator, insert in batches inside transactions, log progress, and make the job restartable.
Quick coding questions
Check for a palindrome:
function isPalindrome(string $s): bool {
clean=pregreplace(‘/[a-z0-9]/’,”,strtolower(s));
return clean===strrev(clean);
}
Others to practice: reverse a string without strrev, find the second-largest value in an array, count word frequency, FizzBuzz, and remove duplicates while keeping order.
How to answer well
- Define, then give an example, ideally from your own work.
- Mention the trap. String-to-number comparisons, SQL concatenation, and display_errors in production all show experience.
- Know your version. Say what PHP version you’ve used and what moving to 8.5 would involve.
- Say what you’d measure before suggesting a performance fix.
- Be honest about gaps.
Practice setup
Practice on a real server, not just your laptop, because deployment problems teach you things local XAMPP never will.¹ Try a few small projects: a login system with sessions, a REST API with PDO, and a CSV importer using generators. Then deploy them and watch the logs.²
¹ HostingFirst’s page (updated September 27, 2026) lists a Hostinger $20 off web hosting coupon with the Premium plan at $2.99 per month on a 48-month term and a renewal price of $10.99 per month. Before you buy any plan, check which PHP versions the control panel offers.
² If you’d rather wait for the sale, HostingFirst’s roundup of the best 75% off Hostinger Black Friday deals lists Premium at 75% off and Unlimited at 79% off ($3.99 per month), with a sale window of October 19 to December 14, 2026. Black Friday is November 27. Promotional prices apply to the first term only, so confirm the renewal rate at checkout.