anantamu.com


Top PHP Interview Questions and Answers (2026 Guide)


PHP Interview Questions?


Table of Contents


Section 1: Basic Syntax

1. Write a PHP program to print: Welcome to PHP Programming

<?php
echo "Welcome to PHP Programming";
?>

2. Create a variable $name and print Hello, Raju

<?php
$name = "Raju";
echo "Hello, " . $name;
?>

3. Add Two Numbers

<?php
$a = 10;
$b = 20;
echo $a + $b;
?>

4. Check Even or Odd

<?php
$num = 8;
if($num % 2 == 0){
    echo "Even";
}else{
    echo "Odd";
}
?>

5. Find Largest of Two Numbers

<?php
$a = 15;
$b = 20;
echo ($a > $b) ? $a : $b;
?>

Section 2: Conditional Statements

6. Check Voting Eligibility

<?php
$age = 18;
if($age >= 18){
    echo "Eligible to vote";
}else{
    echo "Not eligible";
}
?>

7. Check Positive, Negative or Zero

<?php
$num = -5;
if($num > 0){
    echo "Positive";
}elseif($num < 0){
    echo "Negative";
}else{
    echo "Zero";
}
?>

8. Grade Calculation

<?php
$marks = 85;
if($marks >= 90){
    echo "A";
}elseif($marks >= 75){
    echo "B";
}elseif($marks >= 50){
    echo "C";
}else{
    echo "Fail";
}
?>

Section 3: Loops

9. Print 1 to 10

<?php
for($i=1;$i<=10;$i++){
    echo $i."<br>";
}
?>

10. Print Even Numbers (1–20)

<?php
for($i=2;$i<=20;$i+=2){
    echo $i."<br>";
}
?>

11. Multiplication Table of 5

<?php
for($i=1;$i<=10;$i++){
    echo "5 x $i = ".(5*$i)."<br>";
}
?>

12. Sum of 1 to 100

<?php
$sum=0;
for($i=1;$i<=100;$i++){
    $sum+=$i;
}
echo $sum;
?>

13. Factorial

<?php
$num=5;
$fact=1;
for($i=1;$i<=$num;$i++){
    $fact*=$i;
}
echo $fact;
?>

Section 4: Functions

14. Add Function

<?php
function add($a,$b){
    return $a+$b;
}
echo add(10,20);
?>

15. Prime Number Function

<?php
function isPrime($num){
    for($i=2;$i<$num;$i++){
        if($num % $i == 0){
            return "Not Prime";
        }
    }
    return "Prime";
}
echo isPrime(7);
?>

16. Square Function

<?php
function square($num){
    return $num*$num;
}
echo square(4);
?>

Section 5: Arrays

17. Print Colors

<?php
$colors=["Red","Green","Blue","Yellow","Black"];
foreach($colors as $color){
    echo $color."<br>";
}
?>

18. Largest Number in Array

<?php
$arr=[10,25,5,40,15];
echo max($arr);
?>

19. Count Elements

<?php
$arr=[1,2,3,4,5];
echo count($arr);
?>

20. Sort Array

<?php
$arr=[5,2,8,1];
sort($arr);
foreach($arr as $val){
    echo $val."<br>";
}
?>

Section 6: Forms

21. Simple Name Form

<?php
if($_POST){
    echo "Welcome, " . $_POST['name'];
}
?>

<form method="post">
<input type="text" name="name" required>
<input type="submit" value="Submit">
</form>

22. Simple Calculator Form

<?php
if($_POST){
    $a = $_POST['a'];
    $b = $_POST['b'];
    echo "Addition: " . ($a + $b);
}
?>

<form method="post">
<input type="number" name="a" required>
<input type="number" name="b" required>
<input type="submit" value="Calculate">
</form>

23. Registration Form Validation

<?php
if($_POST){
    if(empty($_POST['name'])){
        echo "Name required<br>";
    }
    if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)){
        echo "Invalid Email<br>";
    }
    if(strlen($_POST['password']) < 6){
        echo "Password must be minimum 6 characters";
    }
}
?>

Section 7: PHP + MySQL

24. Database Connection

<?php
$conn = mysqli_connect("localhost","root","","testdb");
if(!$conn){
    die("Connection Failed");
}
?>

25. Insert Data

<?php
mysqli_query($conn,"INSERT INTO students(name) VALUES('Raju')");
?>

26. Fetch Records

<?php
$result = mysqli_query($conn,"SELECT * FROM students");
while($row = mysqli_fetch_assoc($result)){
    echo $row['name']."<br>";
}
?>

27. Update Record

<?php
mysqli_query($conn,"UPDATE students SET name='Ram' WHERE id=1");
?>

28. Delete Record

<?php
mysqli_query($conn,"DELETE FROM students WHERE id=1");
?>

29. Complete CRUD

CRUD means Create, Read, Update, Delete. You combine Insert, Select, Update and Delete queries into one student management system.


Section 8: Sessions & Login

30. Simple Login with Session

<?php
session_start();
$_SESSION['user'] = "Raju";
echo "Login Successful";
?>

31. Restrict Dashboard Page

<?php
session_start();
if(!isset($_SESSION['user'])){
    header("Location: login.php");
}
?>

Advanced Beginner Challenges

32. File Upload

<?php
move_uploaded_file($_FILES['file']['tmp_name'], "uploads/file.jpg");
?>

33. Contact Form Store in Database

<?php
$name = $_POST['name'];
$message = $_POST['message'];
mysqli_query($conn,"INSERT INTO contacts(name,message) VALUES('$name','$message')");
?>

34. Simple Blog System

Create posts table → Insert blog posts → Display using SELECT query.

35. Pagination

<?php
$result = mysqli_query($conn,"SELECT * FROM students LIMIT 0,10");
?>

36. Password Hashing

<?php
$password = password_hash("123456", PASSWORD_DEFAULT);
?>

37. Prevent SQL Injection (Prepared Statement)

<?php
$stmt = $conn->prepare("INSERT INTO students(name) VALUES(?)");
$stmt->bind_param("s",$name);
$stmt->execute();
?>

Bonus: Interview Questions (Theory - Detailed)

38. Difference between == and === in PHP

In PHP, both == and === are comparison operators, but they work differently.

== (Equal Operator)
Compares only the value of two variables. If the values are equal after type conversion, it returns TRUE.

<?php
var_dump(10 == "10");   // TRUE (value is same)
var_dump(true == 1);    // TRUE
?>

=== (Identical Operator)
Compares both value and data type. Returns TRUE only if value AND type are the same.

<?php
var_dump(10 === "10");  // FALSE (different data types)
var_dump(10 === 10);    // TRUE
?>

Interview Tip: Always prefer === for strict comparison to avoid unexpected type conversion.


39. Difference between GET and POST

GET Method:

  • Data is sent through URL.
  • Visible in browser address bar.
  • Limited data size.
  • Less secure.
  • Can be bookmarked.
example.com/page.php?name=Raju

POST Method:

  • Data is sent in HTTP request body.
  • Not visible in URL.
  • No size limitation (practically).
  • More secure than GET.
  • Cannot be bookmarked.
<form method="post">
<input type="text" name="name">
</form>

Interview Tip: Use POST for sensitive data like passwords.


40. Difference between include and require

Both are used to include external PHP files.

include:

  • Shows WARNING if file not found.
  • Script continues execution.
<?php
include("file.php");
echo "Script continues...";
?>

require:

  • Shows FATAL ERROR if file not found.
  • Script stops execution.
<?php
require("file.php");
echo "This will not run if file missing";
?>

Interview Tip: Use require for important files like database connection.


41. Sessions vs Cookies

Sessions:

  • Data stored on server.
  • More secure.
  • Destroyed when browser closes (by default).
<?php
session_start();
$_SESSION['user'] = "Raju";
echo $_SESSION['user'];
?>

Cookies:

  • Data stored in user's browser.
  • Less secure.
  • Can be set with expiry time.
<?php
setcookie("user","Raju",time()+3600);
?>

Interview Tip: Use Sessions for login systems.


42. What is OOP in PHP?

OOP (Object-Oriented Programming) is a programming method that organizes code using Classes and Objects.

Main OOP Concepts:

  • Class – Blueprint of object
  • Object – Instance of class
  • Property – Variables inside class
  • Method – Functions inside class

Encapsulation

Encapsulation is one of the main principles of Object-Oriented Programming (OOP). It means wrapping data (variables) and methods (functions) together inside a class and restricting direct access to them.

In PHP, Encapsulation is achieved using access modifiers:

  • public – Accessible from anywhere
  • private – Accessible only inside the same class
  • protected – Accessible inside the class and its child classes

Encapsulation helps in:

  • Protecting data from unauthorized access
  • Improving security
  • Controlling how data is modified
  • Making code more organized and maintainable
Example of Encapsulation:
<?php
class BankAccount {
    private $balance;  // Cannot access directly

    public function setBalance($amount){
        if($amount > 0){
            $this->balance = $amount;
        }
    }

    public function getBalance(){
        return $this->balance;
    }
}

$account = new BankAccount();
$account->setBalance(5000);
echo $account->getBalance();
?>

In this example, the $balance variable is private. It cannot be accessed directly from outside the class. It can only be modified using public methods (setBalance and getBalance).

Interview Tip: Encapsulation protects internal data and allows controlled access using getter and setter methods.


Inheritance

Inheritance in PHP

Inheritance is one of the main concepts of Object-Oriented Programming (OOP). It allows one class (child class) to inherit properties and methods from another class (parent class).

Inheritance helps in:

  • Code reusability
  • Reducing duplication
  • Improving maintainability
  • Creating logical class hierarchy

In PHP, inheritance is achieved using the extends keyword.

Example of Inheritance:
<?php
class Animal {
    public function sound(){
        echo "Animal makes a sound";
    }
}

class Dog extends Animal {
    public function bark(){
        echo "Dog barks";
    }
}

$dog = new Dog();
$dog->sound(); // Inherited from Animal class
$dog->bark();  // Dog class method
?>

In this example:

  • Animal is the Parent class.
  • Dog is the Child class.
  • Dog inherits the sound() method from Animal.

Interview Tip: Inheritance allows a child class to reuse code from the parent class using the extends keyword.


Polymorphism

Polymorphism in PHP

Polymorphism is one of the core concepts of Object-Oriented Programming (OOP). The word Polymorphism means "many forms".

In PHP, polymorphism allows different classes to define the same method name, but each class can have its own implementation.

This means one interface or method name can behave differently depending on the object.

Why Polymorphism is Important?
  • Improves flexibility
  • Reduces code duplication
  • Makes code easier to extend
  • Supports method overriding

️1. Polymorphism Using Method Overriding
<?php
class Animal {
    public function sound(){
        echo "Animal makes a sound";
    }
}

class Dog extends Animal {
    public function sound(){
        echo "Dog barks";
    }
}

class Cat extends Animal {
    public function sound(){
        echo "Cat meows";
    }
}

$dog = new Dog();
$cat = new Cat();

$dog->sound(); // Dog barks
$cat->sound(); // Cat meows
?>

Here, the sound() method exists in all classes, but each class provides a different implementation. This is called Method Overriding.


2. Polymorphism Using Interfaces
<?php
interface Shape {
    public function area();
}

class Circle implements Shape {
    public function area(){
        return "Area of Circle";
    }
}

class Rectangle implements Shape {
    public function area(){
        return "Area of Rectangle";
    }
}

$circle = new Circle();
$rectangle = new Rectangle();

echo $circle->area();
echo $rectangle->area();
?>

In this example:

  • Shape is an interface.
  • Both classes implement the same method area().
  • Each class defines its own logic.

Types of Polymorphism in PHP
  • Compile-Time Polymorphism: Not directly supported in PHP (no method overloading like Java).
  • Run-Time Polymorphism: Achieved using Method Overriding.

Interview Definition:

Polymorphism in PHP allows objects of different classes to respond to the same method name in different ways. It is achieved through method overriding and interfaces.


Abstraction

<?php
class Student {
    public $name;

    function setName($name){
        $this->name = $name;
    }

    function getName(){
        return $this->name;
    }
}

$obj = new Student();
$obj->setName("Raju");
echo $obj->getName();
?>

Interview Tip: Modern PHP frameworks like Laravel use OOP completely.

Abstraction in PHP

Abstraction is one of the core principles of Object-Oriented Programming (OOP). It means hiding internal implementation details and showing only the essential features of an object.

In simple words, abstraction focuses on what an object does instead of how it does it.

Why Abstraction is Important?
  • Hides complex logic
  • Improves security
  • Reduces code complexity
  • Makes code easier to maintain

How Abstraction is Achieved in PHP?

Abstraction is achieved using:

  • Abstract Classes
  • Interfaces

1. Abstraction Using Abstract Class

An abstract class cannot be instantiated (you cannot create its object directly). It may contain abstract methods (methods without body). Child classes must implement those methods.

<?php
abstract class Vehicle {

    abstract public function startEngine();

    public function stopEngine(){
        echo "Engine stopped";
    }
}

class Car extends Vehicle {

    public function startEngine(){
        echo "Car engine started";
    }
}

$car = new Car();
$car->startEngine();
$car->stopEngine();
?>

In this example:

  • Vehicle is an abstract class.
  • startEngine() is an abstract method (no body).
  • Car class must implement startEngine().

2. Abstraction Using Interface

An interface contains only method declarations. All methods must be implemented by the class.

<?php
interface Payment {
    public function pay($amount);
}

class CreditCard implements Payment {
    public function pay($amount){
        echo "Paid using Credit Card: " . $amount;
    }
}

class UPI implements Payment {
    public function pay($amount){
        echo "Paid using UPI: " . $amount;
    }
}

$payment = new CreditCard();
$payment->pay(1000);
?>

Here:

  • Payment is an interface.
  • CreditCard and UPI must implement pay() method.
  • Different payment methods follow the same structure.

Real-Life Example of Abstraction

When you drive a car:

  • You use the steering and pedals (visible features).
  • You don’t see how the engine works internally.

That is abstraction — hiding internal complexity.


Interview Definition:

Abstraction in PHP is the process of hiding internal implementation details and showing only essential functionality. It is achieved using abstract classes and interfaces.


Difference Between Abstract Class and Interface
  • Abstract class can have both abstract and normal methods.
  • Interface can only have method declarations (no body).
  • A class can extend only one abstract class.
  • A class can implement multiple interfaces.

Interface in PHP

An Interface in PHP is a blueprint of a class. It defines method declarations (without body) that a class must implement.

Interfaces help achieve 100% abstraction because they only contain method signatures.


Key Rules of Interface
  • All methods inside an interface are public by default.
  • Interface methods cannot contain a body.
  • A class must implement all methods of the interface.
  • A class can implement multiple interfaces.
  • Interfaces are declared using the interface keyword.

Basic Example
<?php
interface Animal {
    public function makeSound();
}

class Dog implements Animal {
    public function makeSound(){
        echo "Bark";
    }
}

class Cat implements Animal {
    public function makeSound(){
        echo "Meow";
    }
}

$dog = new Dog();
$dog->makeSound();
?>

In this example:

  • Animal is an interface.
  • Dog and Cat must implement makeSound().
  • Each class provides its own implementation.

Multiple Interface Implementation

A class can implement more than one interface.

<?php
interface Camera {
    public function takePhoto();
}

interface MusicPlayer {
    public function playMusic();
}

class Smartphone implements Camera, MusicPlayer {

    public function takePhoto(){
        echo "Photo Taken";
    }

    public function playMusic(){
        echo "Playing Music";
    }
}

$phone = new Smartphone();
$phone->takePhoto();
$phone->playMusic();
?>

Here Smartphone implements two interfaces.


Interface with Constants

Interfaces can contain constants.

<?php
interface Demo {
    const VERSION = "1.0";
}

echo Demo::VERSION;
?>

Why Use Interfaces?
  • Ensures consistent method structure.
  • Improves code flexibility.
  • Supports loose coupling.
  • Allows multiple inheritance (via interfaces).
  • Makes large applications easier to maintain.

Real-World Example

Payment systems use interfaces.

<?php
interface PaymentMethod {
    public function pay($amount);
}

class CreditCard implements PaymentMethod {
    public function pay($amount){
        echo "Paid using Credit Card";
    }
}

class PayPal implements PaymentMethod {
    public function pay($amount){
        echo "Paid using PayPal";
    }
}
?>

All payment types follow the same structure but have different implementations.


Difference Between Interface and Abstract Class
  • Interface → Only method declarations.
  • Abstract class → Can have both abstract and normal methods.
  • Class can implement multiple interfaces.
  • Class can extend only one abstract class.

Interview Definition

An Interface in PHP is a contract that defines a set of methods which a class must implement. It is used to achieve full abstraction and multiple inheritance in PHP.


Method Overloading in PHP

Method Overloading means defining multiple methods with the same name but with different parameters (number or type of arguments).

❗ Important: PHP does NOT support traditional method overloading like Java or C++. You cannot create multiple methods with the same name in the same class.

However, PHP supports Dynamic Method Overloading using magic methods.


Why PHP Does Not Support Traditional Overloading?
  • PHP does not allow two methods with same name inside one class.
  • If you define same method twice, it will give a fatal error.
Example (This will cause error):
<?php
class Demo {
    function add($a, $b){
        return $a + $b;
    }

    function add($a, $b, $c){  // ❌ Error
        return $a + $b + $c;
    }
}
?>

How PHP Achieves Method Overloading?
PHP uses magic methods:
  • __call() → for inaccessible or undefined methods
  • __callStatic() → for static methods

Example Using __call()
<?php
class Calculator {

    public function __call($method, $arguments){
        if($method == "add"){
            return array_sum($arguments);
        }
    }
}

$calc = new Calculator();

echo $calc->add(10, 20);       // 30
echo $calc->add(10, 20, 30);   // 60
?>

Here:

  • add() method is not defined directly.
  • __call() handles dynamic arguments.
  • This simulates method overloading.

Alternative Way (Using Default Parameters)
<?php
class Calculator {

    function add($a, $b, $c = 0){
        return $a + $b + $c;
    }
}

$calc = new Calculator();

echo $calc->add(10, 20);      // 30
echo $calc->add(10, 20, 30);  // 60
?>

This is a simpler way to simulate overloading in PHP.


Method Overloading vs Method Overriding
  • Overloading: Same method name, different parameters (same class).
  • Overriding: Same method name in parent and child class.

Real-World Use Case
In large applications like payment systems:
  • processPayment($amount)
  • processPayment($amount, $currency)
  • processPayment($amount, $currency, $method)
Since PHP does not allow direct overloading, developers use default parameters or __call().


Interview Definition

Method Overloading in PHP refers to the ability to dynamically handle methods with the same name but different parameters. PHP does not support traditional overloading, but it can be implemented using magic methods like __call() or by using default arguments.


School