Top 200 PHP Interview Questions and Answers
Master backend web development interviews with our ultimate collection of top 200 PHP interview questions, OOP concepts, PDO, security, and expert answers.
Q1. What is PHP?
PHP (Hypertext Preprocessor) is a widely-used open-source server-side scripting language designed primarily for web development.
Q2. What are the main features of PHP?
Key features include simplicity, efficiency, security, platform independence, flexibility, and strong database integration support.
Q3. What is the difference between echo and print?
echo can output multiple strings and has no return value, whereas print outputs a single string and always returns 1, making echo slightly faster.
Q4. What is the difference between single quotes ('') and double quotes ("") in PHP?
Single quotes treat strings literally without variable interpolation or escape sequence parsing. Double quotes evaluate variables and escape sequences (like ).
Q5. How do you define constants in PHP?
Constants are defined using the define() function or the const keyword inside classes. They cannot be changed once set.
Q6. What is the difference between include, require, include_once, and require_once?
include throws a warning if file is missing and continues execution. require throws a fatal error and halts execution. *_once variants prevent duplicate inclusion of the same file.
Q7. What are superglobals in PHP?
Built-in variables that are always accessible across scopes, such as $_GET, $_POST, $_SESSION, $_COOKIE, $_SERVER, $_FILES, and $_REQUEST.
Q8. What is the difference between isset(), empty(), and is_null()?
isset() checks if a variable is set and not NULL. empty() checks if a variable is empty (false, 0, '', null, array()). is_null() checks strictly if a variable is NULL.
Q9. What is type hinting in PHP?
A feature allowing developers to specify the expected data type (like class names, arrays, callables, scalar types) for function arguments and return values.
Q10. What is scalar type declaration?
Enforcing scalar types (int, float, string, bool) in function arguments and return types (introduced in PHP 7).
Q11. What is strict_types in PHP?
A declaration (declare(strict_types=1);) enforcing strict type matching for function arguments and return values.
Q12. What are variable variables in PHP?
Variables whose names are stored in another variable (e.g., $$a where $a = 'hello' becomes $hello).
Q13. What is garbage collection in PHP?
PHP uses reference counting and a cyclic garbage collector to free up memory occupied by unused objects.
Q14. What is OPcache?
A caching engine built into PHP that stores precompiled script bytecode in shared memory, eliminating the need for PHP to load and parse scripts on every request.
Q15. What is Composer?
The standard dependency management tool for PHP, used to install, update, and manage third-party libraries.
Q16. What is composer.json and composer.lock?
composer.json declares project dependencies and constraints. composer.lock locks down exact installed dependency versions for reproducible builds.
Q17. What is autoloading in PHP?
A mechanism (PSR-4 standard) that automatically loads class files without requiring explicit manual include or require statements.
Q18. What is PSR?
PHP Standards Recommendations published by the PHP Framework Interop Group (FIG) to standardize coding styles and practices.
Q19. What is namespace in PHP?
Encapsulation mechanism designed to solve naming collisions between classes, functions, and constants.
Q20. What is the use keyword in PHP?
Used to import namespaces, traits, or pass variables into anonymous function closures by reference/value.
Q21. What are anonymous functions (Closures)?
Functions without a specified name that can be assigned to variables or passed as arguments.
Q22. What are arrow functions in PHP?
A concise syntax for anonymous functions introduced in PHP 7.4 that automatically captures outer scope variables by value (fn($x) => $x + $y).
Q23. What is the spaceship operator (<=>)?
A comparison operator returning -1, 0, or 1 depending on whether the left operand is less than, equal to, or greater than the right operand.
Q24. What is the null coalescing operator (??)?
Returns its first operand if it exists and is not NULL; otherwise, it returns its second operand.
Q25. What is the null coalescing assignment operator (??=)?
Assigns the right-hand value to the left variable only if the left variable is null.
Q26. What is type casting in PHP?
Explicitly converting a variable from one data type to another (e.g., (int)$var).
Q27. What is type juggling?
PHP's automatic implicit conversion of data types based on context during operations.
Q28. What is the difference between == and ===?
== performs loose comparison with type juggling. === performs strict comparison checking both value and exact data type.
Q29. What are magic methods in PHP?
Special methods prefixed with double underscores (__construct, __destruct, __get, __set, __toString, __call) triggered by specific object events.
Q30. What does __construct and __destruct do?
__construct initializes object properties when created. __destruct executes cleanup tasks when an object is destroyed or script terminates.
Q31. What does __get and __set do?
Handled dynamically when accessing or writing to inaccessible or private object properties.
Q32. What does __toString do?
Allows an object to decide how it should react when treated like a string (e.g., when printed).
Q33. What is method chaining?
Calling multiple methods sequentially on the same object in a single statement by returning $this from each method.
Q34. What is late static binding (static::)?
Allows referencing the called class in a context of inheritance rather than the class where the method was defined (self::).
Q35. What is the difference between self:: and static::?
self:: resolves to the class where the code is written, while static:: resolves to the runtime called class.
Q36. What are the four pillars of OOP in PHP?
Encapsulation, Inheritance, Polymorphism, and Abstraction.
Q37. What is Encapsulation?
Restricting direct access to object data and bundling methods that operate on that data using visibility modifiers.
Q38. What are visibility modifiers in PHP?
Keywords (public, protected, private) controlling property and method access scopes.
Q39. What is Inheritance?
A mechanism where a child class inherits properties and methods from a parent class using the extends keyword.
Q40. What is Polymorphism?
The ability of different classes to respond to the same method call in unique ways through method overriding or interfaces.
Q41. What is Abstraction?
Hiding complex implementation details and exposing only essential features using abstract classes or interfaces.
Q42. What is an abstract class?
A class that cannot be instantiated directly and may contain abstract methods that child classes must implement.
Q43. What is an Interface in PHP?
A blueprint defining method signatures that implementing classes must declare, supporting multiple interface implementations.
Q44. What is the difference between abstract classes and interfaces?
Abstract classes can have method bodies, properties, and constructors; interfaces only contain method signatures and constants (no state/properties).
Q45. What are Traits in PHP?
A mechanism for code reuse in single-inheritance languages, allowing developers to horizontally inject methods into multiple classes.
Q46. How do you resolve trait method collision conflicts?
Using the insteadof and as operators inside the consuming class.
Q47. What is final keyword in PHP?
Prevents a class from being inherited or a method from being overridden.
Q48. What is a static property/method?
Properties or methods bound to the class itself rather than an object instance, accessed using ClassName::$prop.
Q49. Can a static method access $this?
No, because $this refers to a specific object instance, whereas static methods exist independently of instances.
Q50. What is cloning an object (clone)?
Creating a shallow copy of an object. Use __clone() magic method to customize deep copying.
Q51. What is object serialization?
Converting an object into a byte stream representation using serialize() or json_encode() for storage or transfer.
Q52. What is __sleep and __wakeup?
__sleep runs before serialization to clean up resources, and __wakeup runs after unserialization to re-establish connections.
Q53. What is dependency injection?
A design pattern where object dependencies are passed (injected) into the class rather than created internally.
Q54. What is a Service Container?
A powerful tool in modern frameworks managing class instantiation and dependency injection wiring.
Q55. What is a Singleton design pattern?
Ensures a class has only one instance and provides a global point of access to it.
Q56. What is a Factory design pattern?
A creational pattern providing an interface for creating objects without specifying their exact concrete classes.
Q57. What is Method Overriding?
Redefining a parent class method in a child class with the same signature.
Q58. What is Method Overloading?
PHP does not support traditional method overloading. It simulates dynamic method calls using magic methods like __call() and __callStatic().
Q59. What is property overloading?
Handling dynamic property access using __get(), __set(), __isset(), and __unset().
Q60. What are anonymous classes?
Classes without a name useful for creating simple, one-off objects on the fly.
Q61. What is covariant and contravariant return types?
Covariance allows a child method to return a more specific subtype. Contravariance allows parameter types to accept broader supertypes.
Q62. What is instanceof operator?
Checks whether an object belongs to a specific class, extends a class, or implements an interface.
Q63. What is type hinting for callables?
Ensuring an argument passed to a function is a valid executable callback.
Q64. What is an exception in PHP?
An object representing an error or unexpected condition that can be thrown and caught using try, catch, and finally blocks.
Q65. What is Throwable interface?
The base interface for any throwable object in PHP (implemented by both Exception and Error).
Q66. What is the difference between Exception and Error?
Exceptions represent catchable application-level errors. Errors represent severe internal engine failures (e.g., fatal type mismatches, call to undefined functions).
Q67. How do you create custom exceptions?
By extending the built-in Exception or RuntimeException class.
Q68. What is constructor property promotion?
A feature (PHP 8) allowing property declaration and assignment directly inside constructor parameter lists.
Q69. What are match expressions?
An expression equivalent to switch cases with strict comparisons (===) that return values (PHP 8).
Q70. What are named arguments?
Passing arguments to functions based on parameter names rather than positional order (PHP 8).
Q71. What are attributes in PHP 8?
Structured metadata annotations added to classes, methods, properties, and functions using #[Attribute] syntax.
Q72. What is weak reference in PHP?
References to objects that do not prevent the object from being destroyed by garbage collection.
Q73. What is fiber in PHP 8.1?
Primitive building blocks for implementing lightweight cooperative concurrency (green threads/coroutines).
Q74. What are readonly properties?
Properties initialized once during construction and immutable afterwards (PHP 8.1+).
Q75. What are enums in PHP 8.1?
Restricted object structures representing a fixed set of constant values (backed or pure enums).
Q76. What are the types of arrays in PHP?
Indexed arrays, Associative arrays (key-value pairs), and Multidimensional arrays.
Q77. What is the difference between array_map() and array_filter()?
array_map() applies a callback function to all elements of an array. array_filter() filters array elements using a callback condition.
Q78. What does array_reduce() do?
Iteratively reduces an array to a single cumulative value using a callback function.
Q79. How do you sort arrays in PHP?
Using sort() (indexed ascending), rsort(), asort() (associative value sort), ksort() (key sort), usort() (custom sort).
Q80. What is the difference between include and require?
include generates a warning on failure and continues execution; require generates a fatal error and terminates execution.
Q81. How do you merge arrays in PHP?
Using array_merge() (re-indexes numeric keys, overwrites string keys) or the spread operator [...$arr1, ...$arr2].
Q82. What does array_unique() do?
Removes duplicate values from an array.
Q83. What is the difference between count() and sizeof()?
They are identical aliases; both return the number of elements in an array or object.
Q84. How do you check if a key exists in an array?
Using array_key_exists() or isset().
Q85. How do you check if a value exists in an array?
Using in_array($value, $array, true) (strict check).
Q86. What is string interpolation?
Inserting variables directly inside double-quoted strings without concatenation.
Q87. How do you split a string into an array?
Using explode(separator, string).
Q88. How do you join array elements into a string?
Using implode(glue, array).
Q89. What is the difference between substr() and mb_substr()?
substr() handles single-byte string slicing, whereas mb_substr() supports multi-byte Unicode strings (UTF-8 safe).
Q90. How do you find string length in PHP?
Using strlen() for bytes or mb_strlen() for character count in multibyte encodings.
Q91. What does strpos() return when a substring is not found?
It returns boolean false. (Always use strict comparison !== false since index 0 evaluates to loose false).
Q92. How do you perform regular expression matching in PHP?
Using PCRE functions like preg_match(), preg_match_all(), and preg_replace().
Q93. What is HEREDOC and NOWDOC?
Syntax for multi-line strings. HEREDOC behaves like double quotes (variable parsing). NOWDOC behaves like single quotes.
Q94. What is string trimming in PHP?
Removing whitespace or specified characters from the ends of strings using trim(), ltrim(), or rtrim().
Q95. What is output buffering in PHP?
Storing script output internally in memory before flushing it to the browser, managed via ob_start(), ob_get_clean(), and ob_flush().
Q96. What are reference parameters in functions?
Passing function arguments by reference using an ampersand (&$var), allowing the function to modify the original variable.
Q97. What is variable scope in PHP?
Defines where variables can be accessed (local scope, global scope, static scope, function parameters).
Q98. What is the global keyword?
Used inside functions to access variables defined in the global execution scope.
Q99. What are static variables inside functions?
Variables that retain their value across multiple function calls (static $count = 0;).
Q100. What is a generator in PHP?
Functions using yield that iterate over data sets without loading the entire collection into memory, saving massive RAM.
Q101. What is callback function?
A function passed as an argument to another function to be executed later (e.g., call_user_func()).
Q102. What is recursive function?
A function that calls itself to solve smaller instances of a problem.
Q103. What is variadic functions (...)?
Accepting a variable number of arguments into an array parameter (e.g., function sum(...$nums)).
Q104. What is argument unpacking?
Unpacking array elements into individual function arguments using ...$arr.
Q105. What is eval() function?
Evaluates a string as PHP code (highly discouraged and insecure).
Q106. What is isset() vs empty() performance difference?
Both are language constructs and execute extremely fast, but empty() handles undefined variables without generating notices.
Q107. How do you parse JSON strings in PHP?
Using json_decode($json, true) (returns associative array) and json_encode($data).
Q108. What does json_last_error() do?
Returns the last error code occurred during JSON encoding or decoding.
Q109. How do you handle file uploads in PHP?
Accessing uploaded file metadata and temporary paths via $_FILES['file'] and moving them using move_uploaded_file().
Q110. How do you read file contents into a string?
Using file_get_contents('file.txt') or line-by-line via file() or fopen().
Q111. How do you write data to files?
Using file_put_contents('file.txt', $data, FILE_APPEND | LOCK_EX).
Q112. What does LOCK_EX do in file operations?
Acquires an exclusive lock on the file during writing to prevent race conditions from concurrent processes.
Q113. How do you check if a file exists and is readable?
Using file_exists(), is_file(), and is_readable().
Q114. How do you delete files in PHP?
Using unlink('file.txt').
Q115. How do you work with directories?
Using scandir(), mkdir(), rmdir(), and opendir().
Q116. What is date and time handling in PHP?
Using the DateTime class and date_default_timezone_set() for accurate timezone management.
Q117. What is timestamp in PHP?
Number of seconds elapsed since Unix Epoch (January 1 1970), retrieved via time().
Q118. How do you calculate date differences in PHP?
Using DateTime::diff() which returns a DateInterval object.
Q119. What is microtime()?
Returns current Unix timestamp with microsecond precision, useful for script execution benchmarking.
Q120. How do you execute external shell commands in PHP?
Using exec(), shell_exec(), system(), or backticks (``), with strict security sanitization.
Q121. What is mail function in PHP?
Sends emails using local mail transfer agents, though PHPMailer or Symfony Mailer via SMTP is standard practice.
Q122. What is URL encoding and decoding?
Using urlencode() / urldecode() for query strings and rawurlencode() for RFC 3986 compliance.
Q123. What is base64 encoding?
Converting binary data into ASCII character strings using base64_encode() and base64_decode().
Q124. What is cryptographically secure random bytes generation?
Using random_bytes($length) and random_int($min, $max) for secure tokens and passwords.
Q125. What is password hashing API in PHP?
Using password_hash($password, PASSWORD_BCRYPT) and password_verify($password, $hash).
Q126. What is PDO?
PHP Data Objects: a lightweight, consistent database abstraction layer for accessing databases in PHP supporting prepared statements.
Q127. Why use PDO over MySQLi?
PDO supports 12+ different database drivers, provides named parameters, and offers consistent object-oriented error handling.
Q128. What is a prepared statement?
An SQL query template compiled by the database beforehand where parameters are bound securely, preventing SQL injection.
Q129. How do you connect to MySQL using PDO?
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8mb4', $user, $pass);
Q130. What is PDO error mode configuration?
Setting $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); to throw exceptions on database errors.
Q131. What is SQL Injection?
A security vulnerability where attackers insert malicious SQL fragments into input fields to manipulate database execution.
Q132. How do you prevent SQL Injection in PHP?
By strictly using PDO or MySQLi prepared statements with bound parameters.
Q133. What is Cross-Site Scripting (XSS)?
Injecting malicious client-side scripts into web pages viewed by other users.
Q134. How do you prevent XSS in PHP?
By sanitizing inputs and escaping outputs using htmlspecialchars($data, ENT_QUOTES, 'UTF-8').
Q135. What is Cross-Site Request Forgery (CSRF)?
An attack forcing authenticated users to execute unwanted actions on a web application.
Q136. How do you prevent CSRF in PHP?
By generating, storing in session, and validating unique cryptographic CSRF tokens on state-changing requests.
Q137. What are Sessions in PHP?
Server-side storage mechanism storing user data across multiple pages identified by a session ID stored in cookies.
Q138. What are Cookies in PHP?
Small text files stored on the user's browser via setcookie().
Q139. What is HttpOnly cookie flag?
Prevents client-side JavaScript access to cookies, mitigating XSS session hijacking attacks.
Q140. What is Secure cookie flag?
Ensures cookies are transmitted exclusively over encrypted HTTPS connections.
Q141. What is SameSite cookie attribute?
Controls whether cookies are sent with cross-site requests (Strict, Lax, None), mitigating CSRF.
Q142. How do you start and destroy sessions?
Using session_start(), session_unset(), and session_destroy().
Q143. What is session fixation attack?
An attack where an adversary sets a user's session ID prior to login. Prevent it via session_regenerate_id(true).
Q144. What is session hijacking?
Stealing an active session ID to impersonate a legitimate user.
Q145. How do you sanitize user input?
Using filter functions like filter_var($email, FILTER_SANITIZE_EMAIL) or filter_input().
Q146. How do you validate user input?
Using validation filters like FILTER_VALIDATE_EMAIL or FILTER_VALIDATE_INT.
Q147. What is MIME type sniffing?
Browsers guessing file types regardless of headers. Prevent it using X-Content-Type-Options: nosniff header.
Q148. What is Content Security Policy (CSP)?
An HTTP header restricting domains from which scripts, images, and resources can load.
Q149. What is Clickjacking?
Tricking users into clicking concealed invisible UI elements using iframe overlays (prevent via X-Frame-Options header).
Q150. What is CORS headers in PHP?
Setting headers like Access-Control-Allow-Origin to control cross-origin resource sharing for APIs.
Q151. What is rate limiting?
Restricting API or login request frequencies per IP address to prevent brute-force attacks.
Q152. What is Two-Factor Authentication (2FA)?
Adding an extra verification layer using TOTP algorithms (Google Authenticator).
Q153. What is JWT in PHP?
JSON Web Tokens used for stateless API authentication, verified using libraries like firebase/php-jwt.
Q154. How do you handle database transactions in PDO?
Using $pdo->beginTransaction(), $pdo->commit(), and $pdo->rollBack().
Q155. What is database indexing?
Creating index structures on table columns to speed up SELECT query execution times.
Q156. What is EXPLAIN in SQL?
Analyzes how MySQL executes a query, helping identify missing indexes and bottlenecks.
Q157. What is normalisation in databases?
Structuring relational database tables to reduce data redundancy and dependency.
Q158. What is denormalization?
Deliberately introducing redundancy to improve read performance.
Q159. What is connection pooling?
Reusing established database connections across multiple requests (native in persistent connections PDO::ATTR_PERSISTENT).
Q160. What is lazy loading vs eager loading in ORMs?
Lazy loading fetches related records on-demand; eager loading fetches them upfront in a single query to prevent N+1 query problems.
Q161. What is the N+1 query problem?
Executing 1 query to fetch parent records, and N additional queries to fetch related child records iteratively.
Q162. What is Eloquent ORM?
The active record implementation ORM bundled with Laravel framework.
Q163. What is Doctrine ORM?
A powerful Data Mapper pattern ORM used in Symfony and standalone PHP applications.
Q164. What is Laravel framework?
A popular full-stack PHP framework known for expressive syntax, MVC architecture, and rich ecosystem.
Q165. What is Symfony framework?
A robust enterprise-grade PHP framework built on reusable components.
Q166. What is middleware in frameworks?
Filters inspecting and handling HTTP requests before reaching controllers or responses before leaving the server.
Q167. What is routing in PHP frameworks?
Mapping URL paths to specific controller action methods.
Q168. What is service container / IoC container?
Manages class dependencies and automated dependency injection resolution.
Q169. What are database migrations in PHP?
Version-controlled PHP scripts managing database schema creation and modifications.
Q170. What are database seeders?
Scripts populating test or default records into database tables.
Q171. What is queue worker in PHP?
Background workers handling time-consuming tasks asynchronously (emails, image processing) off the main request cycle.
Q172. What is caching in PHP applications?
Storing computed results in fast stores like Redis, Memcached, or file cache to reduce DB load.
Q173. What is Redis and how is it used in PHP?
An in-memory data store used for caching, session storage, rate limiting, and pub/sub queues via phpredis extension.
Q174. What is unit testing in PHP?
Testing individual units of code using PHPUnit framework.
Q175. What is PHPUnit?
The standard developer testing framework for PHP.
Q176. What is mocking in tests?
Simulating behavior of complex dependencies (like database calls or external APIs) during unit tests.
Q177. What is Continuous Integration (CI)?
Automated pipeline running tests, static analysis (PHPStan, Psalm), and code style checks on every push.
Q178. What is PHPStan / Psalm?
Static analysis tools catching bugs and type errors in PHP code without executing it.
Q179. What is Xdebug?
A powerful debugging and profiling extension for PHP enabling step-through debugging in IDEs.
Q180. What is error reporting configuration?
Controlling displayed errors using error_reporting(E_ALL); and ini_set('display_errors', '0'); in production.
Q181. How do you log errors in PHP?
Using error_log($message) or logging libraries like Monolog.
Q182. What is Monolog?
A popular logging library for PHP sending logs to files, databases, Slack, or email.
Q183. What is RESTful API design in PHP?
Building stateless APIs communicating via JSON over HTTP verbs (GET, POST, PUT, DELETE).
Q184. How do you handle API request rate limits in PHP?
Using token bucket algorithms stored in Redis or database caches.
Q185. What is cURL extension in PHP?
A library enabling PHP to make HTTP requests to external APIs and web services.
Q186. What is Guzzle?
An extensible PHP HTTP client making sending requests and working with APIs effortless.
Q187. What is Server-Sent Events (SSE)?
A server push technology streaming real-time updates over HTTP connections to clients.
Q188. What are WebSockets in PHP?
Real-time bidirectional communication enabled via Ratchet or Swoole.
Q189. What is Swoole?
An asynchronous event-driven coroutine framework for PHP transforming PHP into a high-performance persistent server.
Q190. What is ReactPHP?
An event-driven non-blocking I/O low-level library for event-loop based concurrency in PHP.
Q191. What is PHP FIG?
PHP Framework Interop Group establishing collaborative standards like PSR-1, PSR-4, PSR-12.
Q192. What is PSR-12 coding style guide?
Extended coding style standard defining indentation, bracket placements, and naming conventions.
Q193. What is PHP version lifecycle support?
PHP releases follow a 2-year active support followed by 1 year of security fixes model per version.
Q194. What is JIT compiler in PHP 8?
Just-In-Time compiler translating bytecode directly into machine code at runtime for performance boosts in CPU-heavy tasks.
Q195. What is the difference between web server and PHP-FPM?
Web servers (Nginx/Apache) handle HTTP networking requests, while PHP-FPM (FastCGI Process Manager) executes PHP scripts.
Q196. What is PHP-FPM process management modes?
Static, dynamic, and on-demand process pool allocation modes.
Q197. How do you optimize PHP application performance?
Enabling OPcache, using Redis caching, indexing database queries, optimizing autoloader dumps, and minimizing file inclusions.
Q198. What is memory limit configuration?
Setting maximum RAM allocated to script execution via memory_limit in php.ini.
Q199. What is max execution time?
Maximum seconds a script is allowed to run before termination (max_execution_time).
Q200. What is the future outlook of PHP?
Continuous performance enhancements via JIT, stronger type safety features, async support improvements, and widespread enterprise adoption.