Skip to main content

1. PHP Basics & Language Features

Floating point numbers (float)​

Junior

Answer: Floating-point numbers have limited precision and are stored in binary format (IEEE 754). This means that some decimal fractions (like 0.1 or 0.2) cannot be represented exactly. Detailed Floating Point Explained


What does PHP stand for and what is its main purpose?​

Junior

Answer: PHP originally stood for "Personal Home Page," but it now stands for "PHP: Hypertext Preprocessor." It is a server-side scripting language designed for web development. Its main purpose is to generate dynamic web content, handle form data, interact with databases, manage sessions, and more.


Is PHP a case-sensitive language?​

Junior

Answer: Yes, PHP is case-sensitive for variable names. However, function names, class names, and built-in constructs (like echo, if, etc.) are case-insensitive.


What are the rules for naming a PHP variable?​

Junior

Answer:

  • Must start with a $ sign.
  • Followed by a letter or underscore.
  • Can only contain letters, numbers, and underscores (A-z, 0-9, and _).
  • Cannot start with a number.
  • Variable names are case-sensitive.

What are the data types in PHP?​

Junior

Answer:

  • Scalar: int, float, string, bool.
  • Compound: array, object, callable, iterable.
  • Special: resource, null. Detailed Data Types Guide

What is the difference between empty(), is_null(), and isset()?​

Junior

Answer:

  • empty(): Returns true if the variable is an empty string, 0, false, null, or an empty array.
  • is_null(): Returns true only if the variable is null.
  • isset(): Returns true if the variable is set and is not null.

What is the difference between echo and print?​

Junior

Answer:

  • echo is a language construct, while print is a function (though it behaves like a construct).
  • echo is slightly faster and can take multiple parameters.
  • print always returns 1, so it can be used in expressions.

What are include(), require(), include_once(), and require_once()?​

Junior

Answer:

  • include(): Includes a file. If it fails, it emits a warning and continues.
  • require(): Includes a file. If it fails, it emits a fatal error and stops execution.
  • *_once(): Similar to their counterparts, but ensure the file is only included once.

What are the different types of arrays in PHP?​

Junior

Answer:

  • Indexed arrays: Arrays with a numeric index.
  • Associative arrays: Arrays with named keys.
  • Multidimensional arrays: Arrays containing one or more arrays.

What is the difference between single-quoted and double-quoted strings?​

Junior

Answer:

  • Single-quoted: Literals. Variables and most escape sequences are not interpreted.
  • Double-quoted: Variables are interpolated, and escape sequences (like \n, \t) are interpreted.

What is the difference between $message and $$message?​

Junior

Answer: $message is a regular variable. $$message is a "variable variable," which uses the value of $message as the name of another variable.


What is meant by "escaping to PHP"?​

Junior

Answer: It refers to embedding PHP code within HTML using tags like <?php ... ?>.


What are the rules to determine the "truth" of any value (truthiness)?​

Junior

Answer: In PHP, values are "truthy" unless they are: null, false, 0, 0.0, "" (empty string), "0", or [] (empty array).


What is the difference between constants and variables?​

Junior

Answer: Constants are defined using define() or const and cannot be changed or undefined once set. Variables can change their value at any time.


Name some built-in constants in PHP.​

Junior

Answer: PHP_VERSION, PHP_OS, DEFAULT_INCLUDE_PATH, DIRECTORY_SEPARATOR, E_ERROR, E_WARNING.


What is the use of explode() and implode()?​

Junior

Answer:

  • explode(): Splits a string into an array by a delimiter.
  • implode(): Joins array elements into a string using a delimiter.

Junior

Answer:

  • unset(): Destroys a variable or an element in an array.
  • unlink(): Deletes a file from the server.

What are Superglobals in PHP?​

Junior

Answer: Predefined variables that are always available in all scopes throughout a script.

  • $_GET: Data passed via URL query parameters.
  • $_POST: Data passed via HTTP POST method (form data).
  • $_FILES: Data about uploaded files.
  • $_COOKIE: Data stored in cookies.
  • $_SESSION: Data stored in the session.
  • $_SERVER: Information about headers, paths, and script locations.
  • $_ENV: Environment variables.
  • $_REQUEST: Contains contents of $_GET, $_POST, and $_COOKIE.
  • $GLOBALS: References all variables available in global scope.

What are Magic Constants in PHP?​

Middle

Answer: Magic constants are predefined constants that change depending on where they are used.

  • __LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS__, __TRAIT__, __METHOD__, __NAMESPACE__, ClassName::class.

What are Generators?​

Middle

Answer: Generators provide an easy way to implement simple iterators using the yield keyword, allowing you to iterate through data without building an array in memory. Generators and yield


What is the difference between a closure and an anonymous function?​

Middle

Answer: An anonymous function is a function without a name. A closure is an anonymous function that can "close over" variables from its parent scope using the use keyword.


What is Type Hinting?​

Middle

Answer: Type hinting allows you to specify the expected data type for function arguments and return values. This helps catch errors and improves code readability.


What is Garbage Collection in PHP?​

Middle

Answer: PHP uses a reference counting mechanism and a cyclic garbage collector to automatically free memory occupied by objects and variables that are no longer reachable.

  • Reference Counting: In PHP 7+, the refcount is moved from the zval itself into the complex value structures (zend_string, zend_array, etc.). Simple types (like int or bool) are not reference-counted. When a refcount reaches zero, the memory is freed.
  • What is a "Cycle"? A cycle occurs when two or more objects point to each other (circular references), preventing their refcounts from reaching zero even after the original variables are unset.
  • How it cleans: When the "root buffer" (suspected cycles) reaches a limit (default 10,000), the collector runs. It temporarily decrements refcounts of internal objects; if a refcount becomes zero, it's marked as garbage and swept (deleted).
  • Performance: GC prevents memory leaks (essential for long-running scripts) but introduces some CPU overhead during collection. It can be manually controlled via gc_collect_cycles().

Detailed Garbage Collection Guide


What is a zval and what is its basic structure?​

Middle Important

Answer: A zval (Zend value) is the fundamental data structure used by the Zend Engine to represent any PHP variable. In PHP 7+, it was significantly optimized to reduce memory usage (down to 16 bytes) and avoid unnecessary heap allocations.

Internal Structure (PHP 7+):

  1. value: An 8-byte union storing the actual data (e.g., lval for integers, dval for doubles, or pointers like *str, *arr, *obj).
  2. u1 (type_info): A 4-byte union containing the type tag (e.g., IS_STRING, IS_LONG) and type flags (indicating if the value is reference-counted or participates in garbage collection).
  3. u2: A 4-byte union used for auxiliary data (e.g., hash collision chains in arrays).

Key Differences from PHP 5:

  • Size: Reduced from 24/32 bytes to 16 bytes.
  • Reference Counting: Moved from the zval itself into the complex value structures (zend_string, zend_array, etc.).
  • Simple Types: Types like null, bool, int, and float are stored directly in the zval and are no longer reference-counted or heap-allocated.

Detailed Zval Structure Guide


What is copy-on-write in PHP, and when does passing by value duplicate data?​

Middle Important

Answer: Copy-on-write (CoW) is an optimization where PHP shares a single zval (memory storage) between multiple variables until one is modified.

  • Read-only: Passing a large array by value only shares the zval (no memory duplication).
  • Modification: Mutating the array triggers a "separation," creating a real copy in memory.
  • Objects: Pass by handle, so property changes are visible outside without the array-style CoW duplication.

Do not use & purely for memory optimization; PHP's CoW is already efficient for read-heavy access. Detailed Copy-on-Write Guide


What is OPCache?​

Middle

Answer: OPCache is a caching engine for PHP that stores precompiled script bytecode in shared memory, eliminating the need for PHP to load and parse scripts on each request.


How does Error Handling work in PHP?​

Middle

Answer: PHP uses several mechanisms:

  • Error Reporting: Configured via error_reporting() and display_errors in php.ini.
  • Try-Catch Blocks: For handling Exceptions and Errors (since PHP 7).
  • Custom Error Handlers: Using set_error_handler() and set_exception_handler().

Common Error Types:

  • E_ERROR: Fatal run-time errors. Execution of the script is halted.
  • E_WARNING: Run-time warnings (non-fatal errors).
  • E_NOTICE: Run-time notices.
  • E_PARSE: Compile-time parse errors.
  • E_DEPRECATED: Warnings about code that will not work in future versions.

What is the lifecycle of a PHP request?​

Middle

Answer:

  1. Request: The web server (e.g., Nginx/Apache) receives an HTTP request.
  2. Handover: The server identifies it as a PHP file and passes it to the PHP processor (like PHP-FPM) via CGI/FastCGI.
  3. Initialization: PHP starts up, loads its configuration (php.ini), and initializes loaded extensions.
  4. Parsing & Compilation: PHP parses the script and compiles it into opcodes (often cached by Opcache).
  5. Execution: The Zend Engine executes the opcodes.
  6. Output: The script generates an HTTP response (headers and body).
  7. Shutdown: PHP cleans up resources, shuts down extensions, and the process may stay alive (in FPM) to handle the next request.

What are the risks of using PHP as a long-lived process (daemon)?​

Senior

Answer: Memory leaks and global state contamination are the biggest risks, as variables and objects persist between requests. Running PHP as a Daemon


How does the Opcache work?​

Senior

Answer: OpCache improves performance by storing precompiled bytecode in shared memory, avoiding the need for PHP to load, parse, and compile scripts on every request.


How does the opcache work since 8.0 and new JIT?​

Senior

Answer: OpCache with JIT (since 8.0) takes it a step further by identifying "hot" code and compiling it into native machine code, which allows the CPU to execute it directly, bypassing the Zend VM's interpretation loop.

PHP JIT Chart


What do you know about JIT?​

Senior

Answer:

  • JIT (Just-In-Time) is highly effective for CPU-intensive computational tasks (like math or image processing) but typically offers minimal benefits for standard web applications that are limited by I/O (database, filesystem).
  • It opens doors for PHP to be used in areas beyond web development, such as machine learning or long-running heavy-computation daemons.

Detailed OpCache and JIT Guide


Why does var_dump(0.1 + 0.2 == 0.3) return bool(false)?​

Senior

Answer: This occurs because floating-point numbers in PHP (and most other languages) follow the IEEE 754 standard, which represents them in binary. Many decimal fractions, such as 0.1 and 0.2, cannot be represented exactly as finite binary fractions.

  • When you add 0.1 + 0.2, the internal result is slightly different from exactly 0.3 (it's approximately 0.30000000000000004).
  • Comparison: Never use == to compare floats. Instead, use a small epsilon: abs(($a + $b) - $c) < 0.00001.

Database and Financial precision:

  • In databases, you must store these values as DECIMAL (or NUMERIC) instead of float or double.
  • Reason: DECIMAL stores numbers as fixed-point values (or strings internally), ensuring that calculations remain exact, which is critical for monetary values. Floating-point types are for approximate scientific values where speed is more important than absolute precision. Detailed Data Types Guide