Home Blog Technical
Technical Job Search 25 min read

Top 50 PHP Interview Questions for Freshers (with Answers) to Land Your First Job

WR

WorkReady Team

Posted on Jan 2, 2026

Preparing for your first PHP developer interview? This comprehensive guide covers the 50 most commonly asked PHP interview questions—from basic syntax to OOP, security, databases, and modern best practices. Master these, and you'll walk into your interview with confidence.

Master the PHP Interview: Your Ultimate Guide for 2025 - Comprehensive infographic covering PHP interview questions, core concepts, security practices, modern PHP toolkit, and interview best practices
Master the PHP Interview: Your Ultimate Guide for 2025 - Comprehensive guide covering PHP interview questions, core concepts, security practices, and modern PHP features

How to Use This Guide

We've organized these questions into categories: Core PHP Basics, Arrays & Strings, Functions, OOP Concepts, Database & MySQL, Security, and Modern PHP. Start from the basics if you're new, or jump to specific sections to brush up on weak areas.

Section 1 Core PHP Basics

1. What is PHP?

PHP (Hypertext Preprocessor) is a server-side scripting language designed for web development. It runs on the server, generates HTML, and sends it to the browser. PHP is open-source, free, and powers over 75% of websites, including WordPress, Facebook, and Wikipedia.

Key point: PHP code executes on the server, not in the browser. Users never see your PHP code—only the HTML output.

2. What's the difference between echo and print?

Both output data to the screen, but there are subtle differences:

  • echo: Can take multiple parameters, slightly faster, no return value
  • print: Takes one parameter, returns 1 (can be used in expressions)
echo "Hello", " ", "World";  // Works
print "Hello World";          // Works
$result = print "Test";       // $result = 1

3. What are the data types in PHP?

PHP supports 8 primitive data types:

Scalar Types

  • • String
  • • Integer
  • • Float (double)
  • • Boolean

Compound Types

  • • Array
  • • Object
  • • Callable
  • • Iterable

Plus two special types: NULL and Resource.

4. What's the difference between == and ===?

This is a very common interview question:

  • == (Loose comparison): Compares values after type juggling
  • === (Strict comparison): Compares both value AND type
"5" == 5    // true (values equal after type juggling)
"5" === 5   // false (string vs integer)
0 == false  // true (both falsy)
0 === false // false (integer vs boolean)

Pro tip: Always use === for comparisons to avoid unexpected behavior.

5. What are superglobals in PHP?

Superglobals are built-in variables available in all scopes:

$_GET

URL query parameters

$_POST

Form data (POST method)

$_SESSION

Session variables

$_COOKIE

Cookie values

$_SERVER

Server/environment info

$_FILES

Uploaded file data

$_REQUEST

GET + POST + COOKIE

$GLOBALS

All global variables

6. What's the difference between include and require?

Both include external PHP files, but handle errors differently:

  • include: Produces a warning (E_WARNING) if file not found, script continues
  • require: Produces a fatal error (E_COMPILE_ERROR) if file not found, script stops

include_once and require_once ensure the file is included only once, preventing redefinition errors.

require_once 'config.php';     // Critical file - stop if missing
include 'optional-widget.php'; // Optional - continue if missing

7. What is NULL in PHP?

NULL represents a variable with no value. A variable is NULL if:

  • It's assigned the constant NULL
  • It hasn't been set to any value yet
  • It has been unset()
$var = NULL;
is_null($var);      // true
isset($var);        // false
empty($var);        // true

8. What's the difference between isset() and empty()?

  • isset(): Returns true if variable exists AND is not NULL
  • empty(): Returns true if variable doesn't exist OR has a "falsy" value
$a = "";
isset($a);  // true (exists, not NULL)
empty($a);  // true (empty string is falsy)

$b = 0;
isset($b);  // true
empty($b);  // true (0 is falsy)

$c = "hello";
isset($c);  // true
empty($c);  // false

9. What are constants in PHP? How do you define them?

Constants are values that cannot be changed once defined. Two ways to create them:

// Method 1: define() function
define("SITE_NAME", "WorkReady");
echo SITE_NAME;

// Method 2: const keyword (PHP 5.3+)
const MAX_USERS = 100;
echo MAX_USERS;

Key differences: const is defined at compile time (faster), define() at runtime (can use in conditionals).

10. What is variable scope in PHP?

PHP has three variable scopes:

  • Global: Declared outside functions, accessible only outside (unless using global keyword)
  • Local: Declared inside a function, only accessible within that function
  • Static: Local variable that retains its value between function calls
$global_var = "I'm global";

function test() {
    global $global_var;    // Access global
    static $count = 0;     // Retains value
    $count++;
    return $count;
}

echo test(); // 1
echo test(); // 2
echo test(); // 3

Section 2 Arrays & Strings

11. What are the types of arrays in PHP?

PHP supports three types of arrays:

  • Indexed arrays: Numeric keys (0, 1, 2...)
  • Associative arrays: Named keys ("name", "age"...)
  • Multidimensional arrays: Arrays within arrays
// Indexed
$fruits = ["Apple", "Banana", "Orange"];

// Associative
$user = ["name" => "John", "age" => 25];

// Multidimensional
$users = [
    ["name" => "John", "age" => 25],
    ["name" => "Jane", "age" => 30]
];

12. Name 5 common array functions in PHP.

count()

Count elements in array

array_push()

Add element to end

array_pop()

Remove last element

array_merge()

Merge two arrays

in_array()

Check if value exists

array_keys()

Get all keys

13. What's the difference between array_merge() and array_combine()?

  • array_merge(): Combines arrays end-to-end
  • array_combine(): Uses one array as keys, another as values
$a = [1, 2];
$b = [3, 4];
array_merge($a, $b);   // [1, 2, 3, 4]

$keys = ["name", "age"];
$values = ["John", 25];
array_combine($keys, $values); // ["name" => "John", "age" => 25]

14. How do you sort arrays in PHP?

PHP provides multiple sorting functions:

sort()

Sort indexed array ascending

rsort()

Sort indexed array descending

asort()

Sort associative by value

ksort()

Sort associative by key

usort()

Sort with custom function

15. What's the difference between single quotes and double quotes?

  • Single quotes: Literal strings, no variable parsing (faster)
  • Double quotes: Variables are parsed, escape sequences work
$name = "John";
echo 'Hello $name';   // Output: Hello $name
echo "Hello $name";   // Output: Hello John
echo "Line1\nLine2";  // Output: Line1 (newline) Line2
echo 'Line1\nLine2';  // Output: Line1\nLine2

16. Name 5 common string functions in PHP.

strlen()

String length

str_replace()

Replace substring

substr()

Extract substring

strpos()

Find position of substring

strtolower()

Convert to lowercase

trim()

Remove whitespace

17. What's the difference between explode() and implode()?

  • explode(): Splits a string into an array using a delimiter
  • implode(): Joins array elements into a string with a glue
$str = "apple,banana,orange";
$arr = explode(",", $str);  // ["apple", "banana", "orange"]

$arr = ["one", "two", "three"];
$str = implode("-", $arr);  // "one-two-three"

Section 3 Functions

18. What is the difference between passing by value and by reference?

  • By value (default): A copy is passed; original unchanged
  • By reference (&): Original variable is modified
function addFiveValue($num) {
    $num += 5;
}

function addFiveRef(&$num) {
    $num += 5;
}

$x = 10;
addFiveValue($x);
echo $x;  // 10 (unchanged)

addFiveRef($x);
echo $x;  // 15 (modified)

19. What are anonymous functions (closures)?

Anonymous functions are functions without a name. They can be assigned to variables, passed as arguments, or returned from other functions.

// Assign to variable
$greet = function($name) {
    return "Hello, $name!";
};
echo $greet("John");  // Hello, John!

// Use as callback
$numbers = [1, 2, 3, 4, 5];
$squared = array_map(function($n) {
    return $n * $n;
}, $numbers);  // [1, 4, 9, 16, 25]

// Use 'use' to access outer variables
$multiplier = 3;
$multiply = function($n) use ($multiplier) {
    return $n * $multiplier;
};

20. What are arrow functions in PHP?

Introduced in PHP 7.4, arrow functions are a shorter syntax for anonymous functions. They automatically capture variables from the parent scope.

// Traditional anonymous function
$multiply = function($n) use ($factor) {
    return $n * $factor;
};

// Arrow function (PHP 7.4+)
$multiply = fn($n) => $n * $factor;

// Example with array_map
$numbers = [1, 2, 3];
$doubled = array_map(fn($n) => $n * 2, $numbers);

21. What is a callback function?

A callback is a function passed as an argument to another function, to be executed later. PHP uses callbacks extensively in array functions.

// Using a named function as callback
function double($n) {
    return $n * 2;
}
$result = array_map('double', [1, 2, 3]);

// Using anonymous function
$result = array_filter([1, 2, 3, 4, 5], function($n) {
    return $n % 2 == 0;  // Keep even numbers
});

// Using arrow function
$result = array_reduce([1, 2, 3], fn($carry, $n) => $carry + $n, 0);

22. What is recursion in PHP?

Recursion is when a function calls itself. It's useful for problems that can be broken down into smaller, similar sub-problems.

// Factorial using recursion
function factorial($n) {
    if ($n <= 1) {
        return 1;  // Base case
    }
    return $n * factorial($n - 1);  // Recursive call
}

echo factorial(5);  // 120 (5 * 4 * 3 * 2 * 1)

Warning: Always have a base case to prevent infinite recursion!

Section 4 Object-Oriented Programming (OOP)

23. What are classes and objects in PHP?

A class is a blueprint/template for creating objects. An object is an instance of a class with actual values.

class Car {
    public $brand;
    public $color;
    
    public function __construct($brand, $color) {
        $this->brand = $brand;
        $this->color = $color;
    }
    
    public function describe() {
        return "A {$this->color} {$this->brand}";
    }
}

// Create objects (instances)
$myCar = new Car("Toyota", "red");
$yourCar = new Car("Honda", "blue");

echo $myCar->describe();  // A red Toyota

24. What are access modifiers (visibility)?

PHP has three access modifiers:

  • public: Accessible from anywhere
  • protected: Accessible within the class and child classes
  • private: Accessible only within the class
class User {
    public $name;        // Anyone can access
    protected $email;    // Class + children only
    private $password;   // This class only
}

25. What is inheritance in PHP?

Inheritance allows a class to inherit properties and methods from another class using the extends keyword.

class Animal {
    protected $name;
    
    public function speak() {
        return "Some sound";
    }
}

class Dog extends Animal {
    public function speak() {
        return "Woof!";  // Override parent method
    }
    
    public function fetch() {
        return "Fetching ball...";
    }
}

$dog = new Dog();
echo $dog->speak();  // Woof!

26. What is the difference between abstract class and interface?

Feature Abstract Class Interface
Methods Can have abstract + concrete All methods are abstract
Properties Can have properties Only constants
Inheritance Single inheritance Multiple interfaces
Keyword extends implements
interface Payable {
    public function pay($amount);
}

abstract class Employee {
    protected $name;
    abstract public function calculateSalary();
    
    public function getName() {
        return $this->name;
    }
}

class Developer extends Employee implements Payable {
    public function calculateSalary() { /* ... */ }
    public function pay($amount) { /* ... */ }
}

27. What are traits in PHP?

Traits are a mechanism for code reuse in single inheritance languages. They allow you to share methods between classes without inheritance.

trait Loggable {
    public function log($message) {
        echo "[LOG] $message";
    }
}

trait Timestampable {
    public function getTimestamp() {
        return date('Y-m-d H:i:s');
    }
}

class User {
    use Loggable, Timestampable;
    
    public function save() {
        $this->log("User saved at " . $this->getTimestamp());
    }
}

28. What are magic methods in PHP?

Magic methods are special methods that start with double underscores (__). They're automatically called in certain situations.

__construct()

Called when object created

__destruct()

Called when object destroyed

__get($name)

Access undefined property

__set($name, $val)

Set undefined property

__toString()

Object to string conversion

__call($name, $args)

Call undefined method

29. What is the difference between self and $this?

  • $this: Refers to the current object instance
  • self: Refers to the class itself (for static members)
class Counter {
    private static $count = 0;  // Static property
    private $id;                // Instance property
    
    public function __construct() {
        self::$count++;         // Access static with self
        $this->id = self::$count;  // Access instance with $this
    }
    
    public static function getCount() {
        return self::$count;    // Static method uses self
    }
}

30. What is method overriding vs method overloading?

  • Overriding: Child class redefines parent method (supported)
  • Overloading: Multiple methods with same name, different parameters (NOT directly supported in PHP)
// Overriding (supported)
class Animal {
    public function speak() { return "..."; }
}

class Cat extends Animal {
    public function speak() { return "Meow"; }  // Override
}

// "Overloading" workaround using __call
class Calculator {
    public function __call($name, $args) {
        if ($name === 'add') {
            return array_sum($args);
        }
    }
}

Section 5 Database & MySQL

31. What is PDO in PHP?

PDO (PHP Data Objects) is a database abstraction layer that provides a uniform interface for working with different databases. It supports prepared statements and is more secure than mysqli.

try {
    $pdo = new PDO(
        "mysql:host=localhost;dbname=myapp",
        "username",
        "password",
        [PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION]
    );
    
    $stmt = $pdo->prepare("SELECT * FROM users WHERE id = ?");
    $stmt->execute([1]);
    $user = $stmt->fetch(PDO::FETCH_ASSOC);
} catch (PDOException $e) {
    echo "Connection failed: " . $e->getMessage();
}

32. What are prepared statements and why use them?

Prepared statements separate SQL structure from data, preventing SQL injection attacks. The database compiles the query once and executes it with different values.

// UNSAFE - vulnerable to SQL injection!
$sql = "SELECT * FROM users WHERE email = '$email'";

// SAFE - using prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = :email");
$stmt->execute(['email' => $email]);

// With positional placeholders
$stmt = $pdo->prepare("INSERT INTO users (name, email) VALUES (?, ?)");
$stmt->execute([$name, $email]);

Critical: Always use prepared statements when user input is involved!

33. What's the difference between PDO and MySQLi?

Feature PDO MySQLi
Database Support 12+ databases MySQL only
API OOP only OOP + Procedural
Named Parameters Yes (:name) No
Prepared Statements Yes Yes

Recommendation: Use PDO for new projects—it's more flexible and portable.

34. How do you fetch data from MySQL in PHP?

// Fetch single row
$stmt = $pdo->query("SELECT * FROM users WHERE id = 1");
$user = $stmt->fetch(PDO::FETCH_ASSOC);

// Fetch all rows
$stmt = $pdo->query("SELECT * FROM users");
$users = $stmt->fetchAll(PDO::FETCH_ASSOC);

// Loop through results
foreach ($users as $user) {
    echo $user['name'];
}

// Fetch modes:
// PDO::FETCH_ASSOC  - Associative array
// PDO::FETCH_OBJ    - Object
// PDO::FETCH_BOTH   - Both (default)
// PDO::FETCH_CLASS  - Custom class

35. What is SQL injection and how do you prevent it?

SQL injection is an attack where malicious SQL code is inserted through user input to manipulate the database.

// Vulnerable code
$email = $_POST['email'];  // User enters: ' OR '1'='1
$sql = "SELECT * FROM users WHERE email = '$email'";
// Becomes: SELECT * FROM users WHERE email = '' OR '1'='1'
// This returns ALL users!

// Prevention methods:
// 1. Prepared statements (best)
$stmt = $pdo->prepare("SELECT * FROM users WHERE email = ?");
$stmt->execute([$email]);

// 2. Escape special characters (less preferred)
$email = $pdo->quote($email);

36. What is a transaction in MySQL/PHP?

A transaction groups multiple database operations into a single unit. Either all operations succeed, or all fail (atomicity).

try {
    $pdo->beginTransaction();
    
    // Deduct from sender
    $pdo->exec("UPDATE accounts SET balance = balance - 100 WHERE id = 1");
    
    // Add to receiver
    $pdo->exec("UPDATE accounts SET balance = balance + 100 WHERE id = 2");
    
    $pdo->commit();  // Save changes
    
} catch (Exception $e) {
    $pdo->rollBack();  // Undo all changes
    throw $e;
}

Section 6 Security

37. How do you hash passwords in PHP?

Use PHP's built-in password_hash() and password_verify() functions. Never use MD5 or SHA1 for passwords!

// Hashing a password (when user registers)
$password = "userPassword123";
$hash = password_hash($password, PASSWORD_DEFAULT);
// Store $hash in database

// Verifying password (when user logs in)
$inputPassword = $_POST['password'];
$storedHash = $user['password'];  // From database

if (password_verify($inputPassword, $storedHash)) {
    echo "Login successful!";
} else {
    echo "Invalid password!";
}

Note: PASSWORD_DEFAULT uses bcrypt and automatically handles salting.

38. What is XSS and how do you prevent it?

Cross-Site Scripting (XSS) is when attackers inject malicious scripts into web pages viewed by other users.

// Vulnerable code
echo "Welcome, " . $_GET['name'];
// User enters: <script>alert('hacked')</script>

// Prevention: Always escape output
echo "Welcome, " . htmlspecialchars($_GET['name'], ENT_QUOTES, 'UTF-8');

// For HTML attributes
echo '<input value="' . htmlspecialchars($value, ENT_QUOTES) . '">';

// For JavaScript context
echo '<script>var data = ' . json_encode($data) . '</script>';

39. What is CSRF and how do you prevent it?

Cross-Site Request Forgery (CSRF) tricks users into performing unwanted actions on sites where they're authenticated.

// Prevention: Use CSRF tokens

// Generate token (on form load)
session_start();
$token = bin2hex(random_bytes(32));
$_SESSION['csrf_token'] = $token;

// Include in form
echo '<input type="hidden" name="csrf_token" value="' . $token . '">';

// Verify token (on form submit)
if (!hash_equals($_SESSION['csrf_token'], $_POST['csrf_token'])) {
    die("CSRF token validation failed!");
}

40. How do you validate and sanitize user input?

// Sanitize - Remove unwanted characters
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);

// Validate - Check if input is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
    echo "Invalid email format";
}

if (!filter_var($age, FILTER_VALIDATE_INT, ['options' => ['min_range' => 18]])) {
    echo "You must be at least 18";
}

// Common filters:
// FILTER_VALIDATE_EMAIL, FILTER_VALIDATE_URL
// FILTER_VALIDATE_INT, FILTER_VALIDATE_IP
// FILTER_SANITIZE_STRING, FILTER_SANITIZE_NUMBER_INT

41. What are sessions and cookies? What's the difference?

Feature Sessions Cookies
Storage Server Browser
Security More secure Can be tampered
Size Limit No limit ~4KB
Expiry When browser closes Set expiry date
// Sessions
session_start();
$_SESSION['user_id'] = 123;
echo $_SESSION['user_id'];
session_destroy();

// Cookies
setcookie("username", "John", time() + 86400);  // 1 day
echo $_COOKIE['username'];
setcookie("username", "", time() - 3600);  // Delete

Section 7 Modern PHP & Best Practices

42. What is Composer and why is it important?

Composer is PHP's dependency manager. It handles packages, autoloading, and version management for your projects.

# Install a package
composer require monolog/monolog

# Update all packages
composer update

# Install from composer.lock
composer install

# Autoload in your code
require 'vendor/autoload.php';
use Monolog\Logger;

43. What are namespaces in PHP?

Namespaces prevent naming conflicts by grouping related classes, functions, and constants under a unique name.

// File: src/Controllers/UserController.php
namespace App\Controllers;

class UserController {
    public function index() { /* ... */ }
}

// File: index.php
use App\Controllers\UserController;
use App\Models\User as UserModel;  // Alias

$controller = new UserController();
$user = new UserModel();

44. What is PSR and why does it matter?

PSR (PHP Standards Recommendations) are coding standards that ensure consistency across PHP projects:

  • PSR-1: Basic coding standard
  • PSR-4: Autoloading standard
  • PSR-12: Extended coding style (replaces PSR-2)

Following PSR standards makes your code readable and maintainable by other developers.

45. What are type declarations in PHP?

Type declarations (type hints) specify expected types for parameters, return values, and properties.

declare(strict_types=1);  // Enable strict mode

class Calculator {
    public function add(int $a, int $b): int {
        return $a + $b;
    }
    
    public function divide(float $a, float $b): ?float {
        if ($b === 0.0) return null;  // Nullable return
        return $a / $b;
    }
}

// PHP 8+ property types
class User {
    public int $id;
    public string $name;
    public ?string $email = null;
}

46. What is the null coalescing operator (??)?

The null coalescing operator returns the first operand if it exists and is not null; otherwise, it returns the second operand.

// Instead of
$username = isset($_GET['user']) ? $_GET['user'] : 'Guest';

// Use
$username = $_GET['user'] ?? 'Guest';

// Chaining
$value = $a ?? $b ?? $c ?? 'default';

// Null coalescing assignment (PHP 7.4+)
$data['user'] ??= 'Anonymous';  // Set if null/undefined

47. What is the spaceship operator (<=>)?

The spaceship operator compares two values and returns -1, 0, or 1. It's useful for sorting.

echo 1 <=> 2;   // -1 (left is smaller)
echo 2 <=> 2;   // 0  (equal)
echo 3 <=> 2;   // 1  (left is larger)

// Perfect for usort
$users = [['age' => 30], ['age' => 20], ['age' => 25]];
usort($users, fn($a, $b) => $a['age'] <=> $b['age']);
// Sorted: 20, 25, 30

48. What are named arguments in PHP 8?

Named arguments allow you to pass arguments by parameter name, skipping optional parameters.

function createUser(
    string $name,
    string $email,
    int $age = 18,
    bool $active = true
) { /* ... */ }

// Traditional - must provide all args in order
createUser("John", "[email protected]", 18, false);

// Named arguments - skip defaults, any order
createUser(
    name: "John",
    email: "[email protected]",
    active: false  // Skip $age, use default
);

49. What is the match expression in PHP 8?

The match expression is a more powerful switch statement that uses strict comparison and returns values.

$status = 2;

// Old switch
switch ($status) {
    case 1:
        $message = "Draft";
        break;
    case 2:
        $message = "Published";
        break;
    default:
        $message = "Unknown";
}

// New match (PHP 8)
$message = match($status) {
    1 => "Draft",
    2 => "Published",
    3, 4 => "Review",     // Multiple values
    default => "Unknown",
};

50. What are constructor property promotion in PHP 8?

Constructor promotion is a shorthand for declaring and initializing class properties in the constructor.

// Before PHP 8
class User {
    private string $name;
    private string $email;
    private int $age;
    
    public function __construct(string $name, string $email, int $age) {
        $this->name = $name;
        $this->email = $email;
        $this->age = $age;
    }
}

// PHP 8 - Constructor promotion
class User {
    public function __construct(
        private string $name,
        private string $email,
        private int $age = 18
    ) {}
}

Much cleaner! The properties are automatically declared and assigned.

Ready to Land Your First PHP Job?

Knowing interview questions is just the start. At WorkReady, we teach you to build real projects, work with agencies, and get hired. Join our Agency Live Cohort to become job-ready in weeks, not years.

📋 Quick Interview Checklist

  • Know == vs === difference
  • Understand OOP concepts
  • Use prepared statements always
  • Hash passwords with password_hash()
  • Escape output with htmlspecialchars()
  • Know array and string functions
  • Understand sessions vs cookies
  • Learn modern PHP 8 features

Keep Reading

LIVE COHORT

Secure Your Spot

₹13,999 ₹18,000

Join 340+ students who switched from "tutorial hell" to paid agency jobs.

Secure & Private. No Spam.

Free PDF

The Agency Roadmap

Get the exact step-by-step checklist senior devs use to evaluate freshers.

100% Secure. No Spam.

Chat with us