anantamu.com
PHP Interview Questions?
<?php echo "Welcome to PHP Programming"; ?>
<?php $name = "Raju"; echo "Hello, " . $name; ?>
<?php $a = 10; $b = 20; echo $a + $b; ?>
<?php
$num = 8;
if($num % 2 == 0){
echo "Even";
}else{
echo "Odd";
}
?>
<?php $a = 15; $b = 20; echo ($a > $b) ? $a : $b; ?>
<?php
$age = 18;
if($age >= 18){
echo "Eligible to vote";
}else{
echo "Not eligible";
}
?>
<?php
$num = -5;
if($num > 0){
echo "Positive";
}elseif($num < 0){
echo "Negative";
}else{
echo "Zero";
}
?>
<?php
$marks = 85;
if($marks >= 90){
echo "A";
}elseif($marks >= 75){
echo "B";
}elseif($marks >= 50){
echo "C";
}else{
echo "Fail";
}
?>
<?php
for($i=1;$i<=10;$i++){
echo $i."<br>";
}
?>
<?php
for($i=2;$i<=20;$i+=2){
echo $i."<br>";
}
?>
<?php
for($i=1;$i<=10;$i++){
echo "5 x $i = ".(5*$i)."<br>";
}
?>
<?php
$sum=0;
for($i=1;$i<=100;$i++){
$sum+=$i;
}
echo $sum;
?>
<?php
$num=5;
$fact=1;
for($i=1;$i<=$num;$i++){
$fact*=$i;
}
echo $fact;
?>
<?php
function add($a,$b){
return $a+$b;
}
echo add(10,20);
?>
<?php
function isPrime($num){
for($i=2;$i<$num;$i++){
if($num % $i == 0){
return "Not Prime";
}
}
return "Prime";
}
echo isPrime(7);
?>
<?php
function square($num){
return $num*$num;
}
echo square(4);
?>
<?php
$colors=["Red","Green","Blue","Yellow","Black"];
foreach($colors as $color){
echo $color."<br>";
}
?>
<?php $arr=[10,25,5,40,15]; echo max($arr); ?>
<?php $arr=[1,2,3,4,5]; echo count($arr); ?>
<?php
$arr=[5,2,8,1];
sort($arr);
foreach($arr as $val){
echo $val."<br>";
}
?>
<?php
if($_POST){
echo "Welcome, " . $_POST['name'];
}
?>
<form method="post">
<input type="text" name="name" required>
<input type="submit" value="Submit">
</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>
<?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";
}
}
?>
<?php
$conn = mysqli_connect("localhost","root","","testdb");
if(!$conn){
die("Connection Failed");
}
?>
<?php
mysqli_query($conn,"INSERT INTO students(name) VALUES('Raju')");
?>
<?php
$result = mysqli_query($conn,"SELECT * FROM students");
while($row = mysqli_fetch_assoc($result)){
echo $row['name']."<br>";
}
?>
<?php mysqli_query($conn,"UPDATE students SET name='Ram' WHERE id=1"); ?>
<?php mysqli_query($conn,"DELETE FROM students WHERE id=1"); ?>
CRUD means Create, Read, Update, Delete. You combine Insert, Select, Update and Delete queries into one student management system.
<?php session_start(); $_SESSION['user'] = "Raju"; echo "Login Successful"; ?>
<?php
session_start();
if(!isset($_SESSION['user'])){
header("Location: login.php");
}
?>
<?php move_uploaded_file($_FILES['file']['tmp_name'], "uploads/file.jpg"); ?>
<?php
$name = $_POST['name'];
$message = $_POST['message'];
mysqli_query($conn,"INSERT INTO contacts(name,message) VALUES('$name','$message')");
?>
Create posts table → Insert blog posts → Display using SELECT query.
<?php $result = mysqli_query($conn,"SELECT * FROM students LIMIT 0,10"); ?>
<?php
$password = password_hash("123456", PASSWORD_DEFAULT);
?>
<?php
$stmt = $conn->prepare("INSERT INTO students(name) VALUES(?)");
$stmt->bind_param("s",$name);
$stmt->execute();
?>
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.
GET Method:
example.com/page.php?name=Raju
POST Method:
<form method="post"> <input type="text" name="name"> </form>
Interview Tip: Use POST for sensitive data like passwords.
Both are used to include external PHP files.
include:
<?php
include("file.php");
echo "Script continues...";
?>
require:
<?php
require("file.php");
echo "This will not run if file missing";
?>
Interview Tip: Use require for important files like database connection.
Sessions:
<?php session_start(); $_SESSION['user'] = "Raju"; echo $_SESSION['user']; ?>
Cookies:
<?php
setcookie("user","Raju",time()+3600);
?>
Interview Tip: Use Sessions for login systems.
OOP (Object-Oriented Programming) is a programming method that organizes code using Classes and Objects.
Main OOP Concepts:
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:
Encapsulation helps in:
<?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 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:
In PHP, inheritance is achieved using the extends keyword.
<?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:
Interview Tip: Inheritance allows a child class to reuse code from the parent class using the extends keyword.
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.
<?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.
<?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:
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.
<?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 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.
Abstraction is achieved using:
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:
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:
When you drive a car:
That is abstraction — hiding internal complexity.
Abstraction in PHP is the process of hiding internal implementation details and showing only essential functionality. It is achieved using abstract classes and interfaces.
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.
<?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:
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.
Interfaces can contain constants.
<?php
interface Demo {
const VERSION = "1.0";
}
echo Demo::VERSION;
?>
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.
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 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.
<?php
class Demo {
function add($a, $b){
return $a + $b;
}
function add($a, $b, $c){ // ❌ Error
return $a + $b + $c;
}
}
?>
<?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:
<?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 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.