issue 117apr 27mmxxvi
est. 2017
Sun, 27 Apr 2026
vol. IX · no. 117
PapersAdda
placement intelligence, since 2017
640+ briefs · 24 campuses · by reservation
verified offers · sourced from r/developersIndia
razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1razorpay₹65.00 LPA· iit-d · sde-1google₹54.00 LPA· iiit-h · swe-imicrosoft₹49.50 LPA· iit-b · sdeatlassian₹38.00 LPA· nit-w · sde-1amazon₹44.20 LPA· bits-p · sde-1uber₹42.00 LPA· iit-kgp · sde-1

Top 50 PHP Interview Questions 2026

19 min read
Interview Questions
Updated: 8 Jun 2026
Aditya Sharma
Aditya's Edit

PapersAdda 2026 Placement Cycle

By Aditya Sharma·Founder & Editor, PapersAdda

What changed in 2026 drives

Mass-recruiter offer letters are flatter for 2026 batch - the 4-5 LPA ASE band has barely budged in three years while inflation eats real wages. Premium tracks (Digital, Pro, Elite, Specialist) are still where the differential lives, and they are entirely test-driven. If you are aiming higher than the default offer, the coding round is not optional pageantry - it is the entire interview.

What I'd actually study for this

  • 01Two solid coding-round answers (1 medium-hard DSA each, with edge-case discussion) > five half-baked ones
  • 02One real project you can defend end-to-end - file paths, design decisions, and what you would change
  • 03One DBMS schema you actually built (not a textbook ER diagram), with at least 3 join-heavy queries written from memory
  • 04Three behavioural STAR stories: failure recovered, conflict handled, ownership taken

Where most candidates trip up

The single biggest mistake is treating company-specific guides as primary prep and DSA as secondary. It is the opposite. Mass recruiters use the test as a filter, but premium tracks at every IT services company use coding to allocate offer band. Spend 70% of prep time on DSA + system fundamentals, 20% on company-specific patterns, 10% on HR rehearsal. Reverse that ratio and you collect the default offer.

Editorial commentary by Aditya Sharma · written for PapersAdda · not generated, not aggregated.

Last Updated: June 2026 | Level: Freshers to 3 Years Experience | Read Time: ~20 min

PHP remains a dominant web backend language, powering a large portion of the web including WordPress, Joomla, and enterprise Laravel applications. Candidates report these questions appearing in PHP developer screening rounds at web agencies and product companies. This guide covers 50 questions from core PHP to modern PHP 8.x features and Laravel basics. Confirm current interview format on the official careers portal for the company you are applying to.

Pair with Laravel Interview Questions 2026 and SQL Interview Questions 2026 for full-stack web preparation.


Table of Contents

  1. PHP Basics (Q1-Q12)
  2. OOP in PHP (Q13-Q25)
  3. PHP 8.x Modern Features (Q26-Q35)
  4. Error Handling and Security (Q36-Q42)
  5. Performance and Architecture (Q43-Q50)
  6. Mock Interview: 5 Questions
  7. FAQ

PHP Basics

Q1. What is PHP and where is it used? Easy

Use caseExample
CMSWordPress, Drupal, Joomla
FrameworkLaravel, Symfony, CodeIgniter
E-commerceMagento, WooCommerce
SaaSMany Indian B2B tools

Q2. What are the data types in PHP? Easy

// Scalar types
$int = 42;
$float = 3.14;
$bool = true;
$string = "hello";

// Compound types
$array = [1, 2, 3];
$object = new stdClass();

// Special types
$null = null;
$resource = fopen("file.txt", "r"); // resource handle

// Type checking
var_dump(gettype($int));     // "integer"
var_dump(is_string($string)); // true

Q3. What is the difference between == and === in PHP? Easy

var_dump(0 == "foo");    // true (loose comparison, "foo" converts to 0)
var_dump(0 === "foo");   // false (strict: different types)
var_dump("1" == 1);      // true (loose)
var_dump("1" === 1);     // false (strict)
var_dump(null == false); // true (loose)
var_dump(null === false);// false (strict)

Always use === for comparisons. PHP's loose type coercion causes famous bugs like "0" == false being true.


Q4. What are PHP arrays? Easy

// Indexed array
$fruits = ["apple", "banana", "cherry"];
echo $fruits[1]; // banana

// Associative array (like a map/hash)
$user = [
    "name" => "Aditya",
    "age"  => 25,
    "city" => "Delhi"
];
echo $user["name"]; // Aditya

// Multi-dimensional
$matrix = [[1, 2], [3, 4]];

// Useful functions
count($fruits);               // 3
array_push($fruits, "date");  // append
array_merge($fruits, $user);  // merge
array_keys($user);            // ["name","age","city"]
array_values($user);          // ["Aditya",25,"Delhi"]
in_array("apple", $fruits);   // true

Q5. What is the difference between include, require, include_once, require_once? Easy

StatementOn file not foundDuplicate load
includeWarning, continuesLoads again
requireFatal error, stopsLoads again
include_onceWarning, continuesSkips duplicate
require_onceFatal error, stopsSkips duplicate
require_once 'config.php';  // most common for config/class files
include 'sidebar.php';       // optional UI components

Q6. What are PHP superglobals? Easy

$_GET     // URL query parameters
$_POST    // Form POST data
$_REQUEST // Combined GET+POST+COOKIE
$_SESSION // Session data
$_COOKIE  // Cookie values
$_SERVER  // Server/environment info ($_SERVER['REQUEST_METHOD'])
$_FILES   // Uploaded files
$_ENV     // Environment variables
$GLOBALS  // All global variables

Security note: Never use superglobal data directly. Always sanitize and validate.


Q7. What is the difference between GET and POST in PHP forms? Easy

FeatureGETPOST
Data locationURL query stringRequest body
VisibilityVisible in URLNot visible
Max size~2 KB (URL limit)Unlimited (server config)
CachingYes (browsers cache)No
Use caseRead operations, searchWrite operations, passwords

Q8. What are sessions and cookies? Medium

// Sessions: server-side storage, identified by session ID cookie
session_start();
$_SESSION['user_id'] = 42;
$name = $_SESSION['username'] ?? 'Guest';
session_destroy(); // logout

// Cookies: client-side storage
setcookie('theme', 'dark', time() + 86400, '/');  // 1 day
$theme = $_COOKIE['theme'] ?? 'light';

// Key difference: sessions store data on server (more secure)
// Cookies store data in browser (can be tampered)

Q9. How do you connect to MySQL in PHP (PDO)? Medium

$dsn = "mysql:host=localhost;dbname=myapp;charset=utf8mb4";
$pdo = new PDO($dsn, 'user', 'password', [
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
]);

// Prepared statement (prevents SQL injection)
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);
$user = $stmt->fetch();

Always use PDO with prepared statements, never mysql_* functions (deprecated since PHP 7.0).


Q10. What is string interpolation and heredoc? Easy

$name = "Aditya";
$age = 25;

// Double quotes: variables interpolated
echo "Hello, $name! You are {$age} years old.";

// Single quotes: no interpolation
echo 'Hello, $name'; // literal: Hello, $name

// Heredoc: multi-line with interpolation
$html = <<<EOT
    <h1>Hello, $name</h1>
    <p>Age: $age</p>
EOT;

// Nowdoc: heredoc without interpolation (like single quotes)
$raw = <<<'EOT'
    No $interpolation here
EOT;

Q11. What are PHP type declarations? Medium

// PHP 7+ typed parameters and return types
function add(int $a, int $b): int {
    return $a + $b;
}

// PHP 8.0 union types
function format(int|float $num): string {
    return number_format($num, 2);
}

// PHP 8.0 nullable
function findUser(?int $id): ?User {
    if ($id === null) return null;
    return User::find($id);
}

// Strict mode (at file top)
declare(strict_types=1);
// Without this: "5" would be accepted as int (coercion)
// With this: "5" as int throws TypeError

Q12. Predict the output: Easy

$a = "10" + 5;
$b = "10 apples" + 5;
$c = "apples" + 5;
var_dump($a, $b, $c);

Output:

int(15)
int(15)
int(5)

Explanation: PHP loosely converts strings to numbers for arithmetic. "10" becomes 10, "10 apples" becomes 10, "apples" becomes 0.


OOP in PHP

Q13. What are the four OOP principles in PHP? Easy

// Encapsulation
class BankAccount {
    private float $balance = 0;
    public function deposit(float $amount): void {
        if ($amount > 0) $this->balance += $amount;
    }
    public function getBalance(): float { return $this->balance; }
}

// Inheritance
class SavingsAccount extends BankAccount {
    private float $interestRate;
    public function __construct(float $rate) {
        $this->interestRate = $rate;
    }
    public function applyInterest(): void { ... }
}

Q14. What are access modifiers in PHP? Easy

class User {
    public string $name;        // accessible anywhere
    protected int $age;         // class + subclasses
    private string $password;   // class only
    
    public static int $count = 0;  // static property
    
    public function __construct(string $name, int $age) {
        $this->name = $name;
        $this->age = $age;
        self::$count++;
    }
}

Q15. What is an abstract class vs interface in PHP? Medium

FeatureAbstract classInterface
InstantiationNoNo
ImplementationCan have concrete methodsPHP 8+: no (only signatures)
MultipleNot multiple inheritanceMultiple interfaces OK
ConstructorYesNo
PropertiesYesConstants only
abstract class Shape {
    abstract public function area(): float;
    public function describe(): string {
        return "I am a shape with area " . $this->area();
    }
}

interface Printable {
    public function print(): void;
}

class Circle extends Shape implements Printable {
    public function __construct(private float $r) {}
    public function area(): float { return M_PI * $this->r ** 2; }
    public function print(): void { echo $this->describe(); }
}

Q16. What are traits in PHP? Medium

trait Timestampable {
    private DateTime $createdAt;
    private DateTime $updatedAt;
    
    public function touch(): void {
        $this->updatedAt = new DateTime();
    }
    public function getCreatedAt(): DateTime { return $this->createdAt; }
}

trait SoftDeletes {
    private ?DateTime $deletedAt = null;
    public function softDelete(): void { $this->deletedAt = new DateTime(); }
    public function isDeleted(): bool { return $this->deletedAt !== null; }
}

class Post {
    use Timestampable, SoftDeletes;
    // gets all methods from both traits
}

Q17. What are magic methods in PHP? Medium

class MagicClass {
    private array $data = [];
    
    public function __get(string $name): mixed {
        return $this->data[$name] ?? null;
    }
    
    public function __set(string $name, mixed $value): void {
        $this->data[$name] = $value;
    }
    
    public function __isset(string $name): bool {
        return isset($this->data[$name]);
    }
    
    public function __toString(): string {
        return json_encode($this->data);
    }
    
    public function __invoke(string $arg): string {
        return "Called with $arg";
    }
}

$obj = new MagicClass();
$obj->username = "Aditya";  // __set
echo $obj->username;         // __get: Aditya
echo $obj("test");           // __invoke: Called with test

Q18. What are static methods and properties? Medium

class Counter {
    private static int $count = 0;
    
    public static function increment(): void {
        self::$count++;
    }
    
    public static function getCount(): int {
        return self::$count;
    }
}

Counter::increment();
Counter::increment();
echo Counter::getCount(); // 2

static members belong to the class, not instances. Access via ClassName::member or self::member inside the class.


Q19. What is late static binding (static::)? Advanced

class ParentClass {
    public static function create(): static {
        return new static();  // creates instance of the CALLING class
    }
    
    public static function getName(): string {
        return static::class;  // late static binding
    }
}

class ChildClass extends ParentClass {}

$parent = ParentClass::create(); // ParentClass instance
$child = ChildClass::create();   // ChildClass instance
echo ChildClass::getName();      // "ChildClass"

self:: always refers to the defining class; static:: refers to the called class.


Q20. What are constructor property promotion (PHP 8.0)? Easy

// Old way
class Point {
    public int $x;
    public int $y;
    public function __construct(int $x, int $y) {
        $this->x = $x;
        $this->y = $y;
    }
}

// PHP 8.0 property promotion
class Point {
    public function __construct(
        public int $x,
        public int $y,
    ) {}
}

$p = new Point(3, 4);
echo $p->x; // 3

Q21. What is the spread operator and named arguments (PHP 8.0)? Medium

// Spread operator
function sum(int ...$nums): int {
    return array_sum($nums);
}
$nums = [1, 2, 3, 4, 5];
echo sum(...$nums); // 15

// Named arguments
function createUser(string $name, int $age = 0, string $role = 'user'): User {
    return new User($name, $age, $role);
}

createUser(age: 25, name: 'Aditya', role: 'admin');
// order doesn't matter with named args

Q22. What is Readonly properties (PHP 8.1)? Medium

class User {
    public function __construct(
        public readonly string $name,
        public readonly string $email,
    ) {}
}

$user = new User('Aditya', '[email protected]');
echo $user->name;  // Aditya
// $user->name = 'other';  // Fatal error: Cannot modify readonly property

Q23. What are Fibers in PHP 8.1? Advanced

$fiber = new Fiber(function(): void {
    $value = Fiber::suspend('first');
    echo "Got: $value\n";
    Fiber::suspend('second');
});

$v1 = $fiber->start();    // "first"
$v2 = $fiber->resume('hello');  // prints "Got: hello", returns "second"

Q24. What are enums in PHP 8.1? Medium

// Basic (pure) enum
enum Status {
    case Active;
    case Inactive;
    case Pending;
}

// Backed enum (with scalar values)
enum Color: string {
    case Red   = 'red';
    case Green = 'green';
    case Blue  = 'blue';
}

$c = Color::Red;
echo $c->value;         // "red"
$c2 = Color::from('green');  // Color::Green
echo $c2->name;         // "Green"

Q25. Predict the output: Medium

class A {
    public function hello(): string { return "A"; }
}
class B extends A {
    public function hello(): string { return parent::hello() . "B"; }
}
class C extends B {
    public function hello(): string { return parent::hello() . "C"; }
}

echo (new C())->hello();

Output: ABC

Explanation: C::hello() calls B::hello(), which calls A::hello() (returns "A"), appends "B" (returns "AB"), then C appends "C" → "ABC".


PHP 8.x Modern Features

Q26. What is the match expression? Easy

// Old switch (loose comparison, no return value)
$result = match($status) {
    'active'   => 'User is active',
    'inactive' => 'User is inactive',
    'banned'   => 'User is banned',
    default    => 'Unknown status',
};
// match uses strict comparison (===)
// match is an expression (returns value)
// match exhaustiveness warning if no default

Q27. What is the null-safe operator (?->)? Medium

// Before PHP 8.0
$city = null;
if ($user !== null) {
    if ($user->getAddress() !== null) {
        $city = $user->getAddress()->getCity();
    }
}

// PHP 8.0+
$city = $user?->getAddress()?->getCity();
// Returns null if any link in chain is null

Q28. What are union types and intersection types? Medium

// Union types (PHP 8.0)
function formatValue(int|float|string $value): string {
    return (string) $value;
}

// Nullable (shorthand for int|null)
function find(?int $id): ?User { ... }

// Intersection types (PHP 8.1) - value must satisfy ALL types
function process(Iterator&Countable $collection): void { ... }

// DNF types (PHP 8.2): (A&B)|null
function handle((Iterator&Countable)|null $c): void { ... }

Q29. What are named arguments in PHP 8.0? Easy

function makeTag(string $tag, string $content, string $class = ''): string {
    $classAttr = $class ? " class=\"$class\"" : '';
    return "<$tag$classAttr>$content</$tag>";
}

// Traditional
makeTag('div', 'Hello', 'container');

// Named: order-independent, skip defaults
makeTag(content: 'Hello', tag: 'div');
makeTag(tag: 'p', content: 'World', class: 'text-lg');

Q30. What is array_is_list()? Easy

array_is_list([]);            // true
array_is_list([1, 2, 3]);     // true (sequential 0-indexed)
array_is_list(['a' => 1]);    // false (associative)
array_is_list([0 => 'a', 1 => 'b']); // true
array_is_list([1 => 'a', 0 => 'b']); // false (wrong order)

Added in PHP 8.1 to distinguish indexed arrays from associative arrays.


Q31. What are never return type and noreturn? Medium

function redirect(string $url): never {
    header("Location: $url");
    exit();
    // Function never returns normally
}

function throwError(string $msg): never {
    throw new RuntimeException($msg);
}

never means the function always throws or exits. The compiler will warn if code follows a never function.


Q32. What is Stringable interface? Easy

class Money {
    public function __construct(
        private int $amount,
        private string $currency
    ) {}
    
    public function __toString(): string {
        return "$this->amount $this->currency";
    }
}

// Money automatically implements Stringable via __toString
function format(string|Stringable $value): string {
    return (string) $value;
}

echo format(new Money(100, 'INR')); // 100 INR

Q33. What are first-class callable syntax (PHP 8.1)? Medium

// Old way
$fn = Closure::fromCallable('strlen');
$fn = Closure::fromCallable([$obj, 'method']);

// PHP 8.1: first-class callables
$strlen = strlen(...);
$arr = ['hello', 'world', 'php'];
$lengths = array_map(strlen(...), $arr);  // [5, 5, 3]

class User {
    public function getName(): string { return $this->name; }
}
$getNames = array_map($user->getName(...), $users);

Q34. What is readonly class (PHP 8.2)? Medium

// All properties are readonly automatically
readonly class Coordinate {
    public function __construct(
        public float $lat,
        public float $lng,
    ) {}
}

$c = new Coordinate(28.6139, 77.2090);
// $c->lat = 0; // Fatal error

Q35. What is array_any() and array_all() (PHP 8.4+)? Easy

$nums = [1, 5, 10, 15, 20];

// PHP 8.4
$hasEven = array_any($nums, fn($n) => $n % 2 === 0); // true
$allPositive = array_all($nums, fn($n) => $n > 0);    // true
$allEven = array_all($nums, fn($n) => $n % 2 === 0);  // false

Error Handling and Security

Q36. What is exception handling in PHP? Medium

class DatabaseException extends RuntimeException {}

function getUser(int $id): array {
    try {
        $result = $pdo->query("SELECT * FROM users WHERE id = $id");
        if (!$result) throw new DatabaseException("Query failed");
        return $result->fetch();
    } catch (DatabaseException $e) {
        error_log($e->getMessage());
        throw $e;  // re-throw
    } catch (PDOException $e) {
        throw new DatabaseException("DB error: " . $e->getMessage(), 0, $e);
    } finally {
        // Always runs: logging, cleanup
    }
}

Q37. How do you prevent SQL injection in PHP? Medium

// WRONG - SQL injection vulnerable
$id = $_GET['id'];
$query = "SELECT * FROM users WHERE id = $id";

// CORRECT - Prepared statement (PDO)
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
$stmt->execute([$_GET['id']]);

// CORRECT - Named placeholders
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email AND active = :active");
$stmt->execute(['email' => $email, 'active' => 1]);

Q38. How do you prevent XSS in PHP? Medium

// WRONG: outputs raw HTML
echo $_GET['name'];

// CORRECT: escape output
echo htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');

// Or use a templating engine (Blade, Twig) which auto-escapes
// In Blade: {{ $name }} is escaped, {!! $name !!} is raw

Q39. What is CSRF and how do you prevent it? Medium

// Generate token and store in session
function generateCsrfToken(): string {
    if (empty($_SESSION['csrf_token'])) {
        $_SESSION['csrf_token'] = bin2hex(random_bytes(32));
    }
    return $_SESSION['csrf_token'];
}

// Include in form
echo '<input type="hidden" name="csrf_token" value="' . generateCsrfToken() . '">';

// Validate on POST
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'] ?? '')) {
    http_response_code(403);
    die('CSRF token mismatch');
}

Q40. What is password hashing in PHP? Medium

// Hash (bcrypt by default)
$hash = password_hash($password, PASSWORD_DEFAULT);
// store $hash in database

// Verify
if (password_verify($inputPassword, $hash)) {
    // correct password
}

// Check if rehash needed (after algorithm change)
if (password_needs_rehash($hash, PASSWORD_DEFAULT)) {
    $newHash = password_hash($password, PASSWORD_DEFAULT);
}

Never use MD5 or SHA1 for passwords. Always use password_hash().


Q41. What is Composer and PSR standards? Medium

# Install dependencies
composer install

# Add package
composer require vendor/package

# Autoloading (PSR-4)
# composer.json:
{
  "autoload": {
    "psr-4": {
      "App\\": "src/"
    }
  }
}

Key PSRs: PSR-1 (basic coding), PSR-4 (autoloading), PSR-7 (HTTP messages), PSR-12 (code style), PSR-3 (logging).


Q42. What is PHP-FPM? Medium

# Nginx config
location ~ \.php$ {
    fastcgi_pass unix:/var/run/php/php8.2-fpm.sock;
    fastcgi_index index.php;
    include fastcgi_params;
}

PHP-FPM supports process pooling, dynamic/static worker count, and per-pool settings. Much more performant than mod_php.


Performance and Architecture

Q43. What is opcode caching and OPcache? Medium

; php.ini
opcache.enable=1
opcache.memory_consumption=128
opcache.interned_strings_buffer=8
opcache.max_accelerated_files=10000
opcache.validate_timestamps=0  ; production (disable for performance)

OPcache can improve PHP performance by 2-10x. Enable in production, set validate_timestamps=0 to skip file modification checks.


Q44. What is Composer autoloading? Medium

// PSR-4 autoloading
// src/User/Repository.php
namespace App\User;

class Repository {
    // ...
}

// Usage (after composer dump-autoload)
require 'vendor/autoload.php';
use App\User\Repository;
$repo = new Repository();

composer dump-autoload generates the autoload map. -o flag optimizes for production.


Q45. What is the MVC pattern in PHP? Medium

Request -> Router -> Controller -> Model (DB query) -> View (HTML)
// Controller
class UserController {
    public function show(int $id): Response {
        $user = User::find($id);      // Model
        return view('user.profile', ['user' => $user]); // View
    }
}

// Model (Eloquent)
class User extends Model {
    protected $fillable = ['name', 'email'];
    public function orders() { return $this->hasMany(Order::class); }
}

Q46. What are PHP generators? Advanced

function fibonacci(): Generator {
    [$a, $b] = [0, 1];
    while (true) {
        yield $a;
        [$a, $b] = [$b, $a + $b];
    }
}

$gen = fibonacci();
for ($i = 0; $i < 10; $i++) {
    echo $gen->current() . " ";
    $gen->next();
}
// 0 1 1 2 3 5 8 13 21 34

// Memory-efficient large file reading
function readLargeFile(string $path): Generator {
    $handle = fopen($path, 'r');
    while (!feof($handle)) {
        yield fgets($handle);
    }
    fclose($handle);
}

Generators are memory-efficient: they produce values on demand instead of building a full array.


Q47. What is declare(strict_types=1)? Easy

declare(strict_types=1); // must be first statement in file

function add(int $a, int $b): int {
    return $a + $b;
}

add(1, 2);     // 3
add(1.5, 2);   // TypeError: argument must be of type int, float given
add("1", 2);   // TypeError

Without strict types, PHP coerces 1.5 to 1 silently. With strict types, it throws.


Q48. What is spl_autoload_register vs Composer autoloading? Medium

// Manual (legacy)
spl_autoload_register(function($class) {
    $file = str_replace('\\', '/', $class) . '.php';
    if (file_exists($file)) require $file;
});

// Composer (modern, preferred)
require 'vendor/autoload.php';
// Handles PSR-4, classmap, files automatically

Composer autoloading is the standard. Use spl_autoload_register only for legacy systems without Composer.


Q49. What is the SplStack, SplQueue, and SplHeap? Advanced

// SplStack: LIFO
$stack = new SplStack();
$stack->push('a');
$stack->push('b');
$stack->push('c');
echo $stack->pop(); // c

// SplQueue: FIFO
$queue = new SplQueue();
$queue->enqueue('task1');
$queue->enqueue('task2');
echo $queue->dequeue(); // task1

// SplMinHeap: priority queue
$heap = new SplMinHeap();
$heap->insert(5);
$heap->insert(2);
$heap->insert(8);
echo $heap->extract(); // 2 (minimum)

Q50. Predict the output: generators. Advanced

function gen(): Generator {
    yield 1;
    yield 2;
    return 'done';
    yield 3; // never reached
}

$g = gen();
foreach ($g as $v) { echo $v . " "; }
echo $g->getReturn();

Output: 1 2 done

Explanation: foreach iterates yielded values (1, 2). return ends the generator; yield 3 is unreachable. getReturn() retrieves the return value after the generator finishes.


Mock Interview: 5 Questions

  1. Implement a Singleton pattern in PHP using static and prevent cloning.
  2. Rewrite a loop-based array transformation to use array_map + array_filter.
  3. Explain the difference between interface and abstract class with a real-world example.
  4. How would you secure a PHP file upload endpoint against malicious uploads?
  5. What is the output of var_dump("0" == false, "0" == null, false == null) and why?

FAQ

Q: Should I learn PHP or Node.js for web development? A: Both have strong job markets. PHP dominates CMS/WordPress/e-commerce; Node.js dominates real-time apps and API servers. For Indian freelancing and web agency work, PHP remains highly practical.

Q: Is Laravel worth learning? A: Yes. Laravel is the most popular PHP framework and is expected knowledge for most PHP developer roles above entry level.

Q: How is PHP 8 different from PHP 7? A: PHP 8.0 brought JIT compilation, match expressions, named arguments, nullsafe operator, union types. PHP 8.1 added fibers, enums, readonly properties. PHP 8.2 added readonly classes and new string functions. Each version significantly improved performance and developer experience.


Related reading: Laravel Interview Questions 2026 | SQL Interview Questions 2026 | JavaScript Interview Questions 2026 | Node.js Interview Questions 2026

Methodology applied to this articlelast verified 8 Jun 2026
Sources used
Public exam-pattern documents, official recruiter pages, and verified candidate reports on r/developersIndia and LinkedIn.
Verification window
Page last edited 8 Jun 2026 by Aditya Sharma. Numbers and patterns sanity-checked against the most recent 2026 cycle drives we tracked.
What we did NOT do
  • No fabricated salary numbers or success rates. If we quote a range, it's sourced.
  • No noun-substituted templates. This article was not generated by swapping company names in a stock prompt.
  • No paid placements, sponsored coaching links, or affiliate-shilled course pushes.
Verification policy: /editorial-standards/. Found something incorrect? Submit a correction - we respond within 48 hours.

Explore this topic cluster

More resources in Interview Questions

Use the category hub to browse similar questions, exam patterns, salary guides, and preparation resources related to this topic.

Paid contributor programme

Sat this this year? Share your story, earn ₹500.

First-person experience reports help future candidates prep smarter. We pay verified contributors ₹500 via UPI per accepted story - with byline.

Submit your story →

Ready to practice?

Take a free timed mock test

Put what you learned into practice. Our mock tests match the 2026 pattern with timer, navigator, reveal, and score breakdown. No signup.

Start Free Mock Test →

Related Articles

More from PapersAdda

Share this guide: