Skip to content

Interview questions

PHP interview questions

Common PHP interview questions with short, correct answers, up to PHP 8.4. Filter by level or topic, or download them as a PDF.

  • 32 questions
  • Updated October 2026

matching

Basics & types

  • 1. What is the difference between == and ===? Junior

    == compares values after type juggling ('1' == 1 is true). === also compares types, so '1' === 1 is false. Use === by default to avoid surprises; since PHP 8, 0 == 'abc' is false, but loose comparison is still easy to get wrong.

  • 2. What is the difference between echo and print? Junior

    Both output strings. echo can take several arguments and returns nothing; print takes one argument and always returns 1, so it can be used in expressions. echo is marginally faster and far more common.

  • 3. What does declare(strict_types=1) do? Mid-level

    It makes scalar type declarations strict for function calls made from that file: passing '5' to an int parameter throws a TypeError instead of being converted. It applies per file, to the calls written in that file.

  • 4. What are nullable and union types? Mid-level

    A nullable type ?string accepts a string or null. A union type (PHP 8.0) accepts any of several types: int|float. PHP 8.2 added DNF types such as (A&B)|null, and mixed accepts anything.

  • 5. isset() vs empty() vs is_null()? Junior

    isset($x) is true when the variable exists and is not null. empty($x) is true for anything falsy ('', 0, '0', [], null, false) or missing. is_null($x) is true only for null and warns if the variable is undefined.

Arrays & strings

  • 6. What is the difference between array_merge() and the + operator? Mid-level

    array_merge() renumbers numeric keys and appends; for string keys the later value wins. + keeps the left array's keys and only adds keys that are missing, so for duplicate keys the left value wins and numeric keys are not appended.

  • 7. How do array_map, array_filter and array_reduce differ? Junior
    • array_map($fn, $array) returns a new array with $fn applied to each element.
    • array_filter($array, $fn) keeps the elements where $fn returns true (keys are preserved).
    • array_reduce($array, $fn, $initial) folds the array into a single value, such as a sum.
  • 8. Single quotes vs double quotes? Junior

    Double-quoted strings parse variables ("Hello $name") and escape sequences like \n; single-quoted strings are literal (only \' and \\ are escapes). Heredoc behaves like double quotes, nowdoc like single quotes.

  • 9. How do you handle multibyte (UTF-8) strings? Mid-level

    Use the mb_ functions (mb_strlen, mb_substr, mb_strtolower). strlen('é') returns 2 because it counts bytes, mb_strlen('é') returns 1. Make sure the database and connection use utf8mb4 too.

Object-oriented PHP

  • 10. Abstract class vs interface? Junior

    An interface only declares methods (and constants) a class must implement; a class can implement many. An abstract class can contain implemented methods, properties and abstract methods; a class can extend only one. Use interfaces for contracts, abstract classes to share code.

  • 11. What are traits? Mid-level

    Traits let you reuse methods in several unrelated classes (horizontal reuse), since PHP has single inheritance. A class uses a trait and gets its methods as if they were written in the class. Conflicts are resolved with insteadof and as.

  • 12. self vs static vs \$this? Mid-level

    $this is the current object. self:: refers to the class where the code is written. static:: uses late static binding: it refers to the class that was actually called, so a parent method calling new static() creates the child class.

  • 13. What are the magic methods you know? Mid-level

    __construct, __destruct, __get / __set (inaccessible properties), __call / __callStatic (inaccessible methods), __toString, __invoke (call the object like a function), __isset, __unset, __clone, __serialize / __unserialize. Frameworks use __call and __get heavily, e.g. Eloquent attributes.

  • 14. Explain the SOLID principles briefly. Senior
    • Single responsibility: a class has one reason to change.
    • Open/closed: extend behaviour without editing existing code.
    • Liskov substitution: subclasses must work wherever the parent is used.
    • Interface segregation: many small interfaces beat one large one.
    • Dependency inversion: depend on abstractions (interfaces), not concrete classes.
  • 15. What is dependency injection? Mid-level

    Passing a class its dependencies (usually through the constructor) instead of creating them inside. It makes code testable (inject a fake) and flexible (swap implementations). A DI container automates building those objects.

Modern PHP (8.x)

  • 16. Name some important PHP 8 features. Mid-level
    • 8.0: named arguments, constructor property promotion, union types, match, nullsafe operator ?->, attributes, JIT.
    • 8.1: enums, readonly properties, first-class callable syntax, fibers, never type.
    • 8.2: readonly classes, DNF types.
    • 8.3: typed class constants, json_validate(), #[\Override].
    • 8.4: property hooks, asymmetric visibility, new without parentheses in chains.
  • 17. match vs switch? Junior

    match is an expression that returns a value, compares strictly (===), has no fall-through and throws UnhandledMatchError when nothing matches. switch compares loosely and needs break statements.

  • 18. What are enums? Mid-level

    Enums (PHP 8.1) define a fixed set of values: enum Status: string { case Active = 'active'; case Banned = 'banned'; }. Backed enums have scalar values (Status::from('active')), can have methods and implement interfaces. They replace class constants for statuses and types.

  • 19. What are readonly properties? Mid-level

    A readonly property can be set once, from inside the class (usually the constructor), and never changed afterwards; writing it again throws an Error. A readonly class (8.2) makes all its properties readonly, good for value objects and DTOs.

  • 20. What are attributes? Senior

    Structured metadata on classes, methods, properties and parameters, written as #[Route('/users')]. They replace docblock annotations and are read with the Reflection API; frameworks use them for routing, validation and ORM mapping.

Errors & exceptions

  • 21. Error vs Exception in PHP 7+? Mid-level

    Both implement Throwable. Exception is for application problems you expect to handle; Error is for engine problems like calling an undefined method or a TypeError. catch (Throwable $e) catches both.

  • 22. What is the purpose of finally? Junior

    A finally block runs after try / catch whether an exception was thrown or not, even when the code returns. Use it to release resources, such as closing a file or a lock.

  • 23. How should errors be handled in production? Mid-level

    Never display errors to users (display_errors=Off); log them instead (log_errors=On) and show a friendly error page. Report exceptions to a log or service such as Sentry, and use specific exception classes to handle expected cases.

Security

  • 24. How do you prevent SQL injection? Junior

    Use prepared statements with bound parameters (PDO: $stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?'); $stmt->execute([$email]);). Never concatenate user input into SQL. Validate input as well, but parameters are the real protection.

  • 25. How do you store passwords securely? Junior

    Use password_hash($password, PASSWORD_DEFAULT) (bcrypt or Argon2, with a salt built in) and check with password_verify(). Never use md5 or sha1 for passwords, and call password_needs_rehash() after login to upgrade old hashes.

  • 26. What is XSS and how do you prevent it? Mid-level

    Cross-site scripting: an attacker gets their JavaScript into your page, for example through a comment. Escape all output for its context: htmlspecialchars($value, ENT_QUOTES, 'UTF-8') in HTML. Templates such as Blade or Twig do it automatically. A Content-Security-Policy adds another layer.

  • 27. What is CSRF? Mid-level

    Cross-site request forgery: another site makes the user's browser send a request (like changing their email) to your site with their cookies. Prevent it with a secret per-session token in forms that the server checks, plus SameSite cookies.

Sessions, HTTP & performance

  • 28. Sessions vs cookies? Junior

    Cookies are stored in the browser and sent with every request; the user can read and change them. Sessions store data on the server; the browser only holds a session id in a cookie. Keep sensitive data in the session, never in plain cookies.

  • 29. What is OPcache? Mid-level

    OPcache stores compiled PHP bytecode in shared memory, so PHP doesn't have to parse and compile scripts on every request. It's one of the biggest free performance wins; in production, opcache.validate_timestamps=0 skips file checks (clear the cache when you deploy).

  • 30. What is Composer and what is the composer.lock file for? Junior

    Composer is PHP's dependency manager and autoloader. composer.json lists the allowed version ranges; composer.lock records the exact installed versions. Commit the lock file and run composer install on servers so everyone gets the same versions.

  • 31. What are PSR standards? Mid-level

    PHP Standards Recommendations from PHP-FIG that make libraries work together: PSR-4 (autoloading), PSR-12 / PER (coding style), PSR-3 (logger interface), PSR-7 (HTTP messages), PSR-11 (container), PSR-15 (middleware).

  • 32. How do generators help with memory? Senior

    A generator function uses yield to return values one at a time instead of building a whole array. Reading a large CSV line by line with a generator keeps memory flat, whatever the file size.

No question matches.

Practise offline

All 32 questions and answers on a printable A4 PDF. Free for newsletter subscribers.

Get the PHP interview questions PDF

Enter your email to download it now. You'll also get new tutorials and cheat sheets, about once a week. Unsubscribe anytime.

Get new articles in your inbox

Practical tutorials and deep dives, about once a week. No spam, unsubscribe anytime.

Privacy policy

Add DEV Talk to your Home Screen

  1. 1 Tap the Share button in Safari's toolbar.
  2. 2 Scroll down and tap Add to Home Screen.
  3. 3 Tap Add. Open it from the Home Screen to read like an app and to turn on notifications with the bell.

We use cookies to improve your experience and analyze traffic. By continuing, you agree to our Privacy Policy.