PHP runs a large share of the web, including WordPress, Laravel and many Indian business websites. These PHP interview questions cover syntax, arrays, sessions and forms for freshers, then OOP, Composer, security, PDO, performance and modern PHP 8 features for experienced PHP developers.
30 questions · Updated
Reading answers is not the same as saying them.Practise PHP questions out loud and get a score, what you missed and a model answer for each one.
Practise free with AIPHP Interview Questions: 30 questions with model answers on this page.
Basic PHP interview questions
Fundamentals, definitions and simple scenarios. Good for freshers and warm-ups.
1. What is PHP, and where is it used?
Answer flow · 3 steps
1
PHP is a server-side scripting language designed for web development.
2
It runs on the server, generates HTML or JSON and sends it to the browser.
3
It powers WordPress, Laravel, Magento, Drupal and many custom websites and APIs, and is supported by almost every web host.
2. What is the difference between echo and print, and between include and require?
echo and print both output text; echo can take multiple arguments and is slightly faster, while print returns 1 so it can be used in expressions. include adds a file and only issues a warning if it is missing, so the script continues. require stops with a fatal error if the file is missing. include_once and require_once prevent the same file being loaded twice.
3. What is the difference between sessions and cookies?
Answer flow · 3 steps
1
Cookies store small data in the user's browser and are sent with every request.
2
Sessions store data on the server, and only a session ID is kept in a cookie.
3
Sessions are better for sensitive data such as the logged-in user, because the user cannot see or change the data. session_start() begins a session and $_SESSION stores values.
4. What data types does PHP support?
Scalar types (int, float, string and bool), compound types (array, object, callable and iterable), and special types (null and resource). PHP is dynamically typed, so a variable's type depends on its value, but you can declare parameter, return and property types, and with declare(strict_types=1) PHP enforces them strictly instead of converting values.
5. What is the difference between == and === in PHP?
== compares values after type juggling, so "10" == 10 is true. === also compares types, so "10" === 10 is false. PHP 8 made string-to-number comparison safer (0 == "abc" is now false), but === is still recommended to avoid surprises, especially with functions such as strpos that can return 0 or false.
6. What kinds of arrays does PHP have?
Answer flow · 3 steps
1
Indexed arrays with numeric keys, associative arrays with string keys such as ["name" => "Ravi", "city" => "Pune"], and multidimensional arrays containing other arrays.
2
All are ordered maps underneath.
3
Common functions include count, in_array, array_key_exists, array_map, array_filter, array_reduce, array_merge, usort and array_column.
7. What are superglobals?
Superglobals are built-in arrays available everywhere: $_GET and $_POST for request data, $_REQUEST combining them, $_SERVER for server and request information, $_SESSION for session data, $_COOKIE, $_FILES for uploads, $_ENV for environment variables and $GLOBALS. Values from them come from users, so they must always be validated.
8. How do you connect to MySQL with PDO?
Create a PDO object with a DSN, username and password, set the error mode to exceptions, and use prepared statements for every query with user input. PDO works with many databases through the same API.
$pdo = new PDO('mysql:host=localhost;dbname=shop;charset=utf8mb4', $user, $pass, [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);
$stmt = $pdo->prepare('SELECT id, name FROM products WHERE category = ?');
$stmt->execute([$category]);
$products = $stmt->fetchAll();
9. What is the difference between isset, empty and is_null?
isset returns true if a variable exists and is not null. empty returns true if a variable does not exist or has a falsy value, such as "", "0", 0, null, false or an empty array. is_null returns true only when the value is null, and warns if the variable is undefined. The null coalescing operator ?? is a concise way to provide defaults.
10. How do you write functions with typed and default parameters?
Answer flow · 3 steps
1
Declare types and defaults in the signature, such as function price(float $amount, float $tax = 0.18): float.
2
Nullable types use ?string, union types string|int, and named arguments let callers skip optional parameters, as in price(amount: 100, tax: 0.05).
3
Variadic parameters (...$items) accept any number of arguments.
11. How do strings work in PHP?
Answer flow · 3 steps
1
Single-quoted strings are literal, while double-quoted strings interpolate variables, such as "Hello $name", and escape sequences like \n.
2
Strings are joined with the dot operator.
3
Useful functions include strlen, str_contains, str_starts_with, str_replace, substr, explode, implode, trim and sprintf, and the mb_ functions handle multibyte text such as Hindi correctly.
Intermediate PHP interview questions
Applied problems, trade-offs and questions about your own projects.
12. What is the difference between GET and POST in PHP forms?
Answer flow · 3 steps
1
GET sends data in the URL query string, read with $_GET, which is visible, bookmarkable and limited in length, and suits searches and filters.
2
POST sends data in the request body, read with $_POST, which suits forms that change data, logins and file uploads.
3
Neither is secure without HTTPS, and all input must be validated.
13. How do you prevent SQL injection in PHP?
Answer flow · 4 steps
1
Use prepared statements with bound parameters through PDO or MySQLi, for example $stmt = $pdo->prepare('SELECT * FROM users WHERE email = ?'); $stmt->execute([$email]).
2
The query and data are sent separately, so input cannot change the SQL.
3
Never build queries by concatenating user input.
4
ORMs such as Eloquent or Doctrine use prepared statements internally.
14. What is Composer?
Composer is PHP's dependency manager. composer.json lists the packages a project needs, composer.lock records exact versions, and composer install downloads them into the vendor folder. It also generates an autoloader following PSR-4, so classes load automatically from their namespaces without manual require statements.
15. What are traits in PHP?
Answer flow · 3 steps
1
Traits let you reuse methods across classes without inheritance, since PHP supports only single inheritance.
2
A trait is declared with the trait keyword and added to a class with use.
3
They suit shared behaviour such as logging or soft deletes, as Laravel uses them heavily, but overusing them can make code harder to follow.
16. How does object-oriented programming work in PHP?
PHP supports classes with properties and methods, visibility (public, protected, private), constructors with property promotion, inheritance with extends (single inheritance), interfaces with implements, abstract classes, traits for code reuse, static members, readonly properties and enums. Type declarations on properties and methods make classes robust.
17. What are the PSR standards?
PSRs are recommendations from the PHP-FIG group that let frameworks and libraries work together. Important ones are PSR-4 (autoloading classes from namespaces and folders), PSR-12 and PER coding style, PSR-3 (logger interface), PSR-7 and PSR-17 (HTTP messages), PSR-11 (container interface) and PSR-15 (HTTP middleware).
18. What is late static binding?
Answer flow · 3 steps
1
Inside a class, self:: refers to the class where the method is written, while static:: refers to the class that was actually called at runtime.
2
So a parent method using new static() or static::create() creates an instance of the child class when called on the child.
3
It is used in fluent APIs and Active Record models such as Eloquent.
19. What are magic methods?
Magic methods start with two underscores and are called automatically: __construct and __destruct, __get and __set for inaccessible properties, __call and __callStatic for undefined methods, __toString for string conversion, __invoke to call an object like a function, __clone, __isset and __unset. Frameworks use them heavily, but overusing them hides behaviour.
20. How should errors and exceptions be handled in PHP?
Answer flow · 3 steps
1
Most errors in PHP 8 throw Error or Exception objects that can be caught with try/catch, with finally for cleanup.
2
Throw specific exception classes for different failures, catch them where you can handle them, and set a global exception handler that logs details and shows a friendly page.
3
In production, display_errors must be off and log_errors on.
21. What does declare(strict_types=1) do?
Answer flow · 3 steps
1
By default PHP converts values to match declared scalar types, so passing "5" to an int parameter works.
2
With declare(strict_types=1) at the top of a file, function calls from that file must pass exactly the declared types, otherwise a TypeError is thrown.
3
It catches bugs early and is standard in modern PHP projects.
22. What are closures and arrow functions in PHP?
Answer flow · 3 steps
1
Anonymous functions (closures) can be stored in variables and passed as callbacks, capturing outside variables explicitly with use ($rate), or by reference with use (&$total).
2
Arrow functions, such as fn($x) => $x * $rate, are single-expression closures that capture outer variables automatically by value.
3
They are common with array_map, array_filter and usort.
High level PHP interview questions
System design, deep internals, leadership and tough follow-ups.
23. What are the main features of PHP 8?
Answer flow · 3 steps
1
The JIT compiler, named arguments, union types, the nullsafe operator ?->, match expressions, constructor property promotion, attributes, and str_contains (PHP 8.0).
Later versions added readonly classes, typed class constants and property hooks (PHP 8.4).
24. How do you secure a PHP web application?
Use prepared statements, escape output with htmlspecialchars to prevent XSS, protect forms with CSRF tokens, hash passwords with password_hash and verify with password_verify, validate and limit file uploads by type and size and store them outside the web root, regenerate session IDs on login, use secure cookie flags, disable error display in production, and keep PHP and dependencies updated.
25. How do you improve PHP application performance?
Use a supported PHP 8 version, enable OPcache so scripts are not recompiled on each request, use PHP-FPM with a tuned process count, cache data and queries in Redis or Memcached, optimise slow database queries and add indexes, use Composer's optimised autoloader, and profile with Xdebug or Blackfire to find bottlenecks.
26. How does a PHP request work with PHP-FPM?
Answer flow · 4 steps
1
A web server such as Nginx passes PHP requests to PHP-FPM, which keeps a pool of worker processes.
2
For each request, a worker runs the script from start to finish and then discards all state, which is called shared-nothing.
3
This makes PHP simple and robust, since memory leaks and crashes do not persist, and OPcache avoids recompiling scripts.
4
Long-running runtimes such as Swoole, RoadRunner and FrankenPHP keep the app in memory instead.
27. How do you test PHP code?
Answer flow · 3 steps
1
PHPUnit is the standard testing framework, and Pest offers a more expressive syntax on top of it.
2
Unit tests cover classes in isolation with mocks, and integration tests use a test database.
3
Static analysis with PHPStan or Psalm catches type errors without running code, and tools such as Rector automate refactoring and upgrades.
28. What is a dependency injection container?
Answer flow · 3 steps
1
A container creates objects and supplies their dependencies automatically, usually by reading constructor type hints (autowiring), so classes receive what they need instead of creating it.
2
This makes code loosely coupled and testable.
3
Laravel's service container and Symfony's DependencyInjection component are common; PHP-DI is a standalone option following PSR-11.
29. Can PHP do asynchronous or long-running work?
Answer flow · 3 steps
1
Traditional PHP handles one request per worker and exits.
2
For background work, queues with workers (Laravel queues, Symfony Messenger) are standard.
3
Fibers (PHP 8.1) provide the foundation for asynchronous libraries such as ReactPHP and AMPHP, and Swoole, RoadRunner and FrankenPHP run PHP as long-lived servers with much higher throughput, which requires careful handling of shared state.
30. How would you modernise a legacy PHP application?
Add tests around critical behaviour first, then upgrade PHP versions step by step with Rector and PHPStan, introduce Composer and autoloading, replace raw mysql_ functions with PDO prepared statements, extract logic from templates into classes, and gradually move routes into a framework such as Laravel or Symfony using the strangler pattern. Deploy small changes often.
Ready to test yourself?Pick your topics and level, answer by voice or text, and get instant feedback. Free.