Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools
PHP

Top 50 PHP Interview Questions

Curated questions covering OOP, sessions, cookies, database connectivity, security, PHP 8 features, and Laravel framework concepts.

01

What is PHP and what are its key features?

PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development. Key features: embedded in HTML, extensive database support, cross-platform, large ecosystem (Laravel, Symfony, WordPress), and PHP 8 features like JIT compilation, named arguments, and union types.

02

What is the difference between echo and print in PHP?

  • echo - outputs one or more strings. No return value. Slightly faster. Can take multiple comma-separated arguments.
  • print - outputs a string. Returns 1. Can be used in expressions.
  • Both are language constructs, not functions. echo is preferred.
Example
echo "Hello", " World"; // multiple args\nprint "Hello";           // returns 1
03

What is the difference between == and === in PHP?

  • == (loose comparison) - compares values after type coercion. "1" == 1 is true.
  • === (strict comparison) - compares both value and type. "1" === 1 is false.
  • Always use === to avoid unexpected type juggling bugs.
Example
var_dump("1" == 1);   // bool(true)\nvar_dump("1" === 1);  // bool(false)\nvar_dump(0 == "foo"); // bool(true) in PHP 7, bool(false) in PHP 8
04

What is the difference between include, require, include_once, and require_once?

  • include - includes a file. Emits a warning if file not found but continues execution.
  • require - includes a file. Emits a fatal error if file not found and stops execution.
  • include_once / require_once - same as above but checks if the file has already been included and skips if so.
  • Use require_once for class/function files to prevent duplicate declarations.
05

What is the difference between GET and POST in PHP?

  • $_GET - data sent via URL query string. Visible in URL. Limited size (~2KB). Used for non-sensitive data and searches.
  • $_POST - data sent in request body. Not visible in URL. No size limit (server-configured). Used for forms and sensitive data.
  • $_REQUEST - contains both $_GET and $_POST data.
06

What are PHP sessions and how do they work?

Sessions store user data on the server across multiple pages. PHP assigns a unique session ID (stored in a cookie or URL). Data is stored in $_SESSION superglobal.

Example
session_start(); // must be called before any output\n$_SESSION["user_id"] = 42;\n$_SESSION["username"] = "Alice";\n\n// Destroy session\nsession_destroy();\nunset($_SESSION);
07

What is the difference between sessions and cookies?

  • Sessions - data stored on the server. More secure. Expires when browser closes (by default). Identified by session ID cookie.
  • Cookies - data stored in the browser. Less secure (user can modify). Can persist long-term. Limited to ~4KB.
Example
// Cookie\nsetcookie("username", "Alice", time() + 86400, "/"); // 1 day\necho $_COOKIE["username"];\n\n// Session\nsession_start();\n$_SESSION["username"] = "Alice";
08

What is PDO and why is it preferred over mysql_ functions?

PDO (PHP Data Objects) is a database abstraction layer providing a consistent interface for multiple databases. It supports prepared statements (preventing SQL injection), multiple database drivers, and named parameters. mysql_ functions are deprecated and removed in PHP 7.

Example
$pdo = new PDO("mysql:host=localhost;dbname=mydb", $user, $pass);\n$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);\n\n$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");\n$stmt->execute(["email" => $email]);\n$user = $stmt->fetch(PDO::FETCH_ASSOC);
09

What are prepared statements and how do they prevent SQL injection?

Prepared statements separate SQL code from data. The query structure is sent to the database first, then data is bound separately. The database treats bound values as data, never as SQL code, preventing injection.

Example
// Vulnerable\n$sql = "SELECT * FROM users WHERE id = " . $_GET["id"];\n\n// Safe with prepared statement\n$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");\n$stmt->execute([$_GET["id"]]);
10

What is the difference between mysqli and PDO?

  • mysqli - MySQL-specific. Supports both procedural and OOP styles. Slightly faster for MySQL.
  • PDO - database-agnostic. OOP only. Supports 12+ databases. Better for portability.
  • Use PDO for new projects unless you need MySQL-specific features.
11

What is OOP in PHP and what are its four pillars?

  • Encapsulation - bundling data and methods; using access modifiers (public, protected, private).
  • Inheritance - a class extends another using extends keyword.
  • Polymorphism - method overriding; same method name, different behavior in subclasses.
  • Abstraction - abstract classes and interfaces define contracts without implementation.
12

What is the difference between abstract class and interface in PHP?

  • Abstract class - can have abstract and concrete methods, properties, and constructors. A class can extend only one abstract class.
  • Interface - only method signatures (PHP 8 allows constants). A class can implement multiple interfaces.
  • Use abstract class for shared base implementation; interface for defining contracts.
Example
abstract class Animal {\n  abstract public function speak(): string;\n  public function breathe(): void { echo "breathing"; }\n}\n\ninterface Swimmable {\n  public function swim(): void;\n}
13

What is the difference between public, protected, and private in PHP?

  • public - accessible from anywhere.
  • protected - accessible within the class and subclasses.
  • private - accessible only within the class itself.
14

What is the difference between static and non-static methods/properties?

  • Static - belong to the class, not instances. Accessed with ClassName::method(). Cannot use $this.
  • Non-static - belong to instances. Accessed with $this->method().
Example
class Counter {\n  private static int $count = 0;\n  public static function increment(): void { self::$count++; }\n  public static function getCount(): int { return self::$count; }\n}\nCounter::increment();\necho Counter::getCount(); // 1
15

What is the difference between self, static, and parent in PHP?

  • self - refers to the class where the method is defined. Does not support late static binding.
  • static - refers to the class that was called at runtime (late static binding). Supports inheritance correctly.
  • parent - refers to the parent class.
Example
class Base {\n  public static function create(): static { return new static(); } // late static binding\n}\nclass Child extends Base {}\n$obj = Child::create(); // returns Child instance, not Base
16

What is the difference between traits and interfaces in PHP?

  • Interface - defines a contract (method signatures). No implementation.
  • Trait - provides method implementations that can be reused in multiple classes. Solves the single inheritance limitation.
Example
trait Timestampable {\n  public function getCreatedAt(): string { return $this->created_at; }\n  public function touch(): void { $this->updated_at = date("Y-m-d H:i:s"); }\n}\n\nclass User {\n  use Timestampable;\n}
17

What are PHP 8 named arguments?

Named arguments allow passing arguments by parameter name, in any order, and skipping optional parameters.

Example
function createUser(string $name, int $age = 0, string $role = "user"): array {\n  return compact("name", "age", "role");\n}\n\n// Named arguments - skip age, set role\ncreateUser(name: "Alice", role: "admin");
18

What are PHP 8 union types?

Union types allow a parameter or return type to accept multiple types.

Example
function processInput(int|string $input): int|string {\n  return is_int($input) ? $input * 2 : strtoupper($input);\n}\n\nprocessInput(5);       // 10\nprocessInput("hello"); // "HELLO"
19

What is the PHP 8 match expression?

match is a stricter alternative to switch. It uses strict comparison (===), returns a value, does not fall through, and throws UnhandledMatchError for unmatched values.

Example
$status = 2;\n$label = match($status) {\n  1 => "Active",\n  2, 3 => "Pending",\n  4 => "Inactive",\n  default => "Unknown"\n};\n// No break needed, returns value directly
20

What are PHP 8 nullsafe operators?

The nullsafe operator (?->) short-circuits the chain and returns null if any part is null, instead of throwing an error.

Example
// Before PHP 8\n$city = null;\nif ($user !== null && $user->getAddress() !== null) {\n  $city = $user->getAddress()->getCity();\n}\n\n// PHP 8 nullsafe\n$city = $user?->getAddress()?->getCity();
21

What is the difference between array_map, array_filter, and array_reduce?

  • array_map(callback, array) - applies callback to each element, returns new array.
  • array_filter(array, callback) - returns elements where callback returns true.
  • array_reduce(array, callback, initial) - reduces array to a single value.
Example
$nums = [1, 2, 3, 4, 5];\narray_map(fn($x) => $x * 2, $nums);      // [2,4,6,8,10]\narray_filter($nums, fn($x) => $x % 2);   // [1,3,5]\narray_reduce($nums, fn($c, $x) => $c + $x, 0); // 15
22

What is the difference between array_push and $array[] = ?

  • $array[] = value - adds a single element. Faster, no function call overhead.
  • array_push($array, val1, val2) - adds one or more elements. Slightly slower.
  • Prefer $array[] = for single element additions.
23

What is the difference between array_merge and array_replace?

  • array_merge - merges arrays. Numeric keys are re-indexed. String keys from later arrays overwrite earlier ones.
  • array_replace - replaces values in the first array with values from subsequent arrays by key. Numeric keys are preserved.
Example
$a = [1, 2, "x" => "a"];\n$b = [3, "x" => "b"];\narray_merge($a, $b);   // [1, 2, "x"=>"b", 3] - numeric re-indexed\narray_replace($a, $b); // [3, 2, "x"=>"b"] - key 0 replaced
24

What is the difference between isset() and empty()?

  • isset($var) - returns true if variable exists and is not null.
  • empty($var) - returns true if variable is falsy: 0, "", "0", null, false, [], or undefined.
Example
$a = 0;\nvar_dump(isset($a));  // true (exists, not null)\nvar_dump(empty($a));  // true (0 is falsy)
25

What is the difference between unset() and null assignment?

  • unset($var) - destroys the variable. It no longer exists. isset() returns false.
  • $var = null - variable still exists but has null value. isset() returns false, but the variable is still in scope.
26

What is the difference between list() and array destructuring?

Both extract values from arrays. list() is the older syntax; [] destructuring (PHP 7.1+) is the modern equivalent.

Example
$coords = [10, 20, 30];\n\n// list()\nlist($x, $y, $z) = $coords;\n\n// Array destructuring (modern)\n[$x, $y, $z] = $coords;\n\n// With keys\n["name" => $name, "age" => $age] = $user;
27

What is the difference between heredoc and nowdoc in PHP?

  • Heredoc (<<
  • Nowdoc (<<<'EOT') - like single-quoted strings. Variables are NOT interpolated. Useful for code templates.
Example
$name = "Alice";\n$heredoc = <<<EOT\nHello $name\nEOT; // "Hello Alice"\n\n$nowdoc = <<<'EOT'\nHello $name\nEOT; // "Hello $name" (literal)
28

What is the difference between password_hash() and md5() for passwords?

  • md5() / sha1() - fast hashing algorithms. NOT suitable for passwords - too fast, vulnerable to brute force and rainbow tables.
  • password_hash() - uses bcrypt by default. Slow by design. Includes salt automatically. Use with password_verify().
Example
$hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]);\n\nif (password_verify($inputPassword, $hash)) {\n  // authenticated\n}
29

What is XSS and how do you prevent it in PHP?

XSS (Cross-Site Scripting) injects malicious scripts into web pages. Prevent by escaping output with htmlspecialchars() before displaying user input.

Example
// Vulnerable\necho $_GET["name"];\n\n// Safe\necho htmlspecialchars($_GET["name"], ENT_QUOTES, "UTF-8");\n\n// Or use a template engine (Twig auto-escapes by default)
30

What is CSRF and how do you prevent it in PHP?

CSRF (Cross-Site Request Forgery) tricks users into submitting requests they did not intend. Prevent with CSRF tokens: generate a unique token per session, include it in forms, and validate on submission.

Example
// Generate token\n$_SESSION["csrf_token"] = bin2hex(random_bytes(32));\n\n// In form\necho '<input type="hidden" name="csrf_token" value="' . $_SESSION["csrf_token"] . '">'\n\n// Validate\nif (!hash_equals($_SESSION["csrf_token"], $_POST["csrf_token"])) {\n  die("CSRF validation failed");\n}
31

What is the difference between header() and echo in PHP?

  • header() - sends HTTP headers. Must be called before any output. Used for redirects, content type, caching.
  • echo - outputs content to the response body.
Example
// Redirect\nheader("Location: /dashboard");\nexit;\n\n// JSON response\nheader("Content-Type: application/json");\necho json_encode($data);
32

What is the difference between json_encode and json_decode?

  • json_encode($value, $flags) - converts PHP value to JSON string.
  • json_decode($json, $assoc) - converts JSON string to PHP value. Pass true for associative array, false/null for stdClass object.
Example
$data = ["name" => "Alice", "age" => 30];\n$json = json_encode($data);  // {"name":"Alice","age":30}\n\n$obj = json_decode($json);        // stdClass\n$arr = json_decode($json, true);  // associative array
33

What is the difference between file_get_contents and fopen/fread?

  • file_get_contents() - reads entire file into a string. Simple, one-liner. Also works with URLs.
  • fopen/fread/fclose - low-level file handling. Better for large files (read in chunks) or when you need more control.
Example
// Simple\n$content = file_get_contents("file.txt");\n\n// Chunked reading\n$handle = fopen("large.txt", "r");\nwhile (!feof($handle)) {\n  $chunk = fread($handle, 8192);\n}\nfclose($handle);
34

What is the difference between PHP 8 constructor property promotion and traditional constructors?

Constructor property promotion (PHP 8) combines property declaration and constructor assignment into one.

Example
// Traditional\nclass User {\n  private string $name;\n  private int $age;\n  public function __construct(string $name, int $age) {\n    $this->name = $name;\n    $this->age = $age;\n  }\n}\n\n// PHP 8 promotion\nclass User {\n  public function __construct(\n    private string $name,\n    private int $age\n  ) {}\n}
35

What are PHP fibers?

Fibers (PHP 8.1) are lightweight cooperative concurrency primitives. A Fiber can be paused with Fiber::suspend() and resumed later. They are the foundation for async PHP frameworks.

Example
$fiber = new Fiber(function(): void {\n  $value = Fiber::suspend("first");\n  echo "Got: $value\n";\n});\n\n$result = $fiber->start();    // "first"\n$fiber->resume("hello");      // "Got: hello"
36

What are PHP enums?

Enums (PHP 8.1) are a type-safe way to define a set of named constants. Backed enums have string or int values.

Example
enum Status {\n  case Active;\n  case Inactive;\n}\n\n// Backed enum\nenum Color: string {\n  case Red = "red";\n  case Blue = "blue";\n}\n\necho Color::Red->value; // "red"\n$color = Color::from("blue"); // Color::Blue
37

What is the difference between array_key_exists and isset for array keys?

  • array_key_exists($key, $array) - returns true if the key exists, even if the value is null.
  • isset($array[$key]) - returns false if the key does not exist OR if the value is null.
Example
$arr = ["key" => null];\nvar_dump(array_key_exists("key", $arr)); // true\nvar_dump(isset($arr["key"]));            // false (value is null)
38

What is the difference between array_search and in_array?

  • in_array($needle, $haystack) - checks if a value exists in an array. Returns bool.
  • array_search($needle, $haystack) - searches for a value and returns its key. Returns false if not found.
Example
$fruits = ["apple", "banana", "cherry"];\nin_array("banana", $fruits);       // true\narray_search("banana", $fruits);   // 1 (key)
39

What is the difference between usort, uasort, and uksort?

  • usort($array, $callback) - sorts by value using callback. Re-indexes numeric keys.
  • uasort($array, $callback) - sorts by value using callback. Preserves key-value associations.
  • uksort($array, $callback) - sorts by key using callback.
Example
$users = [["name"=>"Bob","age"=>30],["name"=>"Alice","age"=>25]];\nusort($users, fn($a,$b) => $a["age"] <=> $b["age"]);
40

What is the difference between PHP closures and regular functions?

Closures are anonymous functions that can capture variables from the enclosing scope using use keyword. Regular functions cannot access outer scope variables.

Example
$multiplier = 3;\n$multiply = function($x) use ($multiplier) {\n  return $x * $multiplier;\n};\necho $multiply(5); // 15\n\n// Arrow function (PHP 7.4) - auto-captures\n$multiply = fn($x) => $x * $multiplier;
41

What is the difference between PHP arrow functions and closures?

  • Closure (function() use ($var)) - must explicitly capture outer variables with use.
  • Arrow function (fn() =>) - automatically captures outer variables by value. Single expression only.
Example
$factor = 2;\n$double = fn($x) => $x * $factor; // auto-captures $factor\necho $double(5); // 10
42

What is the difference between PHP interfaces and abstract classes for dependency injection?

  • Interface - best for DI. Type-hint against the interface, inject any implementation. Enables easy mocking in tests.
  • Abstract class - useful when sharing implementation. Less flexible for DI.
Example
interface LoggerInterface {\n  public function log(string $message): void;\n}\n\nclass UserService {\n  public function __construct(private LoggerInterface $logger) {}\n}
43

What is the difference between PHP 8 readonly properties and constants?

  • readonly property (PHP 8.1) - can be set once (in constructor). Instance-level. Can be typed.
  • const - class-level constant. Cannot be changed. No type declaration.
Example
class User {\n  public readonly string $id;\n  const VERSION = "1.0";\n  public function __construct(string $id) {\n    $this->id = $id; // can only be set here\n  }\n}
44

What is the difference between PHP generators and arrays for large datasets?

  • Array - loads all data into memory at once. Fast random access but memory-intensive for large datasets.
  • Generator - yields one value at a time. Constant memory usage regardless of dataset size.
Example
// Array: loads all 1M rows into memory\n$rows = $pdo->query("SELECT * FROM logs")->fetchAll();\n\n// Generator: one tl-row at a time\nfunction getLogs(PDO $pdo): Generator {\n  $stmt = $pdo->query("SELECT * FROM logs");\n  while ($row = $stmt->fetch()) yield $row;\n}
45

What is the difference between PHP 8 intersection types and union types?

  • Union types (int|string) - value must be one of the listed types.
  • Intersection types (Countable&Iterator) - value must satisfy ALL listed types simultaneously. Only works with interfaces and classes.
Example
// Union type\nfunction process(int|string $input): void {}\n\n// Intersection type (PHP 8.1)\nfunction processCollection(Countable&Iterator $collection): void {}
46

What is the difference between PHP 8 never return type and void?

  • void - function returns nothing (no return statement or return;).
  • never (PHP 8.1) - function never returns normally. It always throws an exception or calls exit(). Useful for error handlers.
Example
function redirect(string $url): never {\n  header("Location: $url");\n  exit;\n}\n\nfunction logMessage(): void {\n  echo "logged"; // returns normally\n}
47

What is the difference between PHP 8 first class callable syntax and traditional callbacks?

First class callable syntax (PHP 8.1) creates a Closure from any callable using the ... syntax, providing a cleaner alternative to array callbacks and string function names.

Example
// Traditional\nusort($arr, ["MyClass", "compare"]);\narray_map("strtoupper", $strings);\n\n// First class callable (PHP 8.1)\nusort($arr, MyClass::compare(...));\narray_map(strtoupper(...), $strings);
48

What is the difference between PHP 8 DNF types and regular types?

DNF (Disjunctive Normal Form) types (PHP 8.2) allow combining union and intersection types: (A&B)|C means "implements both A and B, OR is of type C".

Example
// DNF type (PHP 8.2)\nfunction process((Countable&Iterator)|array $input): void {\n  // accepts: object implementing both Countable and Iterator, OR an array\n}
49

What is the difference between PHP 8 str_contains, str_starts_with, and str_ends_with?

PHP 8 introduced three readable string helper functions replacing strpos() hacks.

Example
$str = "Hello World";\nstr_contains($str, "World");    // true\nstr_starts_with($str, "Hello"); // true\nstr_ends_with($str, "World");   // true\n\n// Before PHP 8\nstrpos($str, "World") !== false; // verbose
50

What is the difference between PHP 8 throw as expression and traditional throw?

PHP 8 allows throw to be used as an expression, enabling it in arrow functions, ternary operators, and null coalescing.

Example
// PHP 8 throw as expression\n$value = $input ?? throw new InvalidArgumentException("Required");\n$name = fn($x) => $x ?: throw new ValueError("Empty");\n\n// Traditional (PHP 7)\nif ($input === null) {\n  throw new InvalidArgumentException("Required");\n}

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.