All PHP Interview Questions & Answers

All PHP interview questions with simple answers. Covers variables, operators, strings, arrays, functions, loops, OOP, file handling, MySQL, security, sessions and new PHP 8 features.

Can we print multiple variables in a single echo statement in PHP?

Yes. You can print many variables in one echo statement. There are three common ways: separate them with a comma, join them with the dot (.) operator, or put them inside double quotes.

<?php
$name = "Robin";
$city = "Delhi";

echo $name, " lives in ", $city, "<br>";      // comma
echo $name . " lives in " . $city . "<br>";   // dot operator
echo "$name lives in $city";                  // double quotes
?>

Output:

Tutorials Class - Output Window

Robin lives in Delhi
Robin lives in Delhi
Robin lives in Delhi

Variables are replaced by their values only inside double quotes. Single quotes print the text as it is.

How to check the data type of a variable in PHP?

Use var_dump() to see the type and value, gettype() to get the type name, or the is_ functions (like is_int(), is_string(), is_array()) to test a type.

<?php
$a = 343;
$b = "Hello";
$c = 3.14;
$d = [1, 2];

var_dump($a);
echo gettype($b) . "<br>";
var_dump(is_float($c));
echo gettype($d);
?>

Output:

Tutorials Class - Output Window

int(343)
string
bool(true)
array

Note: For a float, gettype() returns the word “double” (an old name). From PHP 8 you can use get_debug_type(), which returns “float”.

In PHP you do not write the data type when creating a variable, PHP decides it from the value. Learn more in PHP Data Types.

Can a single variable store both digits and characters in PHP?

Yes. If you put digits and characters together inside quotes, PHP stores them as a string. PHP is a loosely typed language, so you do not need to declare the type.

<?php
$variable = "Contact:24/7";

echo $variable . "<br>";
echo gettype($variable) . "<br>";

// The same variable can store another type later
$variable = 24;
echo gettype($variable);
?>

Output:

Tutorials Class - Output Window

Contact:24/7
string
integer

Remember that the value in quotes, like "24", is a string and not a number, even if it has only digits. Read PHP Data Types for more.

What is NULL in PHP?

NULL is a special data type in PHP that has only one value, NULL. It means “no value”. NULL is not same as 0, empty string or false.

A variable is NULL in three cases: when you assign NULL to it, when it was never created, or when you remove it with unset().

<?php
$x = "Hello PHP!";
$x = null;

var_dump($x);
var_dump(is_null($x));
var_dump(isset($x));
?>

Output:

Tutorials Class - Output Window

NULL
bool(true)
bool(false)

To check for NULL use is_null() or === null. The isset() function returns false for a NULL variable.

What is the difference between echo and print in PHP?

echo and print both are used to show output in PHP. They are language constructs, so brackets are optional. The main differences are in the table below.

echoprint
Returns nothingAlways returns 1
Can take many values separated by commaTakes only one value
Can not be used inside an expressionCan be used inside an expression
<?php
echo "Hello", " ", "World", "<br>";   // many parameters

$r = print "Hi";                      // print returns 1
echo "<br>" . $r;
?>

Output:

Tutorials Class - Output Window

Hello World
Hi
1

People say echo is a little faster than print, but the difference is so small that you will never notice it. Use echo in most cases.

What is the constant() function in PHP?

The constant() function returns the value of a constant when you have the name of the constant as a string. It is useful when the constant name is stored in a variable or created at run time.

<?php
define("SITE_NAME", "Tutorials Class");

class App {
    const VERSION = "2.0";
}

echo constant("SITE_NAME") . "<br>";

$name = "SITE_NAME";
echo constant($name) . "<br>";

echo constant("App::VERSION");
?>

Output:

Tutorials Class - Output Window

Tutorials Class
Tutorials Class
2.0

If the constant does not exist, PHP 8 throws an Error. Check it first with defined(). Read PHP Constants for the basics.

How to stop the execution of a PHP script?

Use the exit() function to stop a PHP script. You can also write die(), it works exactly same. Any code after it will not run.

<?php
echo "Start<br>";

exit("Stopped here");

echo "This line never runs";
?>

Output:

Tutorials Class - Output Window

Start
Stopped here

To stop only a loop, use break instead. A full explanation is in PHP exit() function.

How to redirect a page in PHP?

Use the header() function with the Location header to redirect to another page. Always call exit after it, so the rest of the script does not run.

<?php
header("Location: https://tutorialsclass.com/");
exit;
?>

For a permanent redirect, pass the status code as the third parameter.

<?php
header("Location: https://tutorialsclass.com/new-page/", true, 301);
exit;
?>
Note: The header() function must be called before any output (even a space or blank line). Otherwise PHP shows a “headers already sent” warning. See PHP header() function.

What is the use of isset() in PHP?

isset() checks whether a variable is set and is not NULL. It returns true if the variable exists and has a value, otherwise false.

<?php
$name = "Robin";

var_dump(isset($name));
var_dump(isset($age));
?>

Output:

Tutorials Class - Output Window

bool(true)
bool(false)

It is mostly used with forms, for example isset($_POST["email"]), to avoid “undefined index” warnings. Read the full chapter PHP isset() function, and learn the difference with empty().

How to get the current session id in PHP?

Use the session_id() function. It returns the id of the current session. Call session_start() before it, otherwise you get an empty string.

<?php
session_start();

echo "Session id: " . session_id();
?>

Output:

Sample output, your id will be different

Session id: 7f2k9d8s1l0a3q5p9c4v6b2n8m

The id is a random text and it changes for every new session. After a user logs in, create a new id with session_regenerate_id(true), it is a good security habit. See PHP Session and PHP Security Tips.

How to create a class and object in PHP?

To create a class in PHP, use the class keyword followed by the class name. A class is like a blueprint, and an object is a real thing made from that blueprint using the new keyword.

Inside a class you can keep variables (called properties) and functions (called methods).

<?php
class Student {
    public $name;

    public function sayHello() {
        return "Hello, my name is " . $this->name;
    }
}

// Create an object using the new keyword
$student1 = new Student();
$student1->name = "Robin";

echo $student1->sayHello();
?>

Output:

Tutorials Class - Output Window

Hello, my name is Robin

You can create many objects from same class, and each object keeps its own values. Read more in PHP Class and PHP OOP Introduction.

What is the difference between unlink() and unset() in PHP?

unlink() deletes a file from the file system. unset() removes a variable from memory. They do very different jobs.

unlink()unset()
Deletes a file from the serverDestroys a variable
Takes the file name or pathTakes the variable
Returns true or falseReturns nothing
The file is gone for everOnly the variable becomes undefined
<?php
$file = "notes.txt";
file_put_contents($file, "Hello");   // create a file

unlink($file);
echo file_exists($file) ? "File exists<br>" : "File deleted<br>";

$name = "Robin";
unset($name);
var_dump(isset($name));
?>

Output:

Tutorials Class - Output Window

File deleted
bool(false)

Be careful with unlink(), a deleted file can not be taken back. Never pass a file name that comes from user input without checking it.

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

public, protected and private are access modifiers (also called visibility). They decide who can use a property or a method of a class.

KeywordCan be accessed from
publicAnywhere: inside the class, in child classes and outside the class
protectedInside the class and in its child classes only
privateInside the same class only
<?php
class Account {
    public $name = "Robin";
    protected $type = "Savings";
    private $pin = 1234;
}

$acc = new Account();

echo $acc->name;   // works, it is public
// echo $acc->pin; // Fatal error, private property can not be accessed outside
?>

Output:

Tutorials Class - Output Window

Robin

If you try to read a private or protected property from outside the class, PHP stops with a fatal error. To give controlled access, we normally write public methods (getters and setters) inside the class.

Note: The words transient and volatile are from Java, they do not exist in PHP.

What is the use of ksort() in PHP?

ksort() sorts an array by its keys in ascending order (A to Z, 1 to 9). It keeps the key and value pairs together. To sort the keys in reverse order use krsort().

<?php
$age = ["Robin" => 25, "Anil" => 30, "Zoya" => 22];

ksort($age);
print_r($age);
?>

Output:

Tutorials Class - Output Window

Array
(
[Anil] => 30
[Robin] => 25
[Zoya] => 22
)

<?php
$age = ["Robin" => 25, "Anil" => 30, "Zoya" => 22];

krsort($age);
print_r($age);
?>

Output:

Tutorials Class - Output Window

Array
(
[Zoya] => 22
[Robin] => 25
[Anil] => 30
)

Both functions sort the original array (they do not return a new one). To sort by value use asort() and arsort().

Is multiple inheritance supported in PHP?

No. PHP does not support multiple inheritance for classes. A class can extend only one parent class, so class C extends A, B gives an error.

But there are two ways to get similar result:

  • Interfaces: a class can implement many interfaces.
  • Traits: a class can use many traits to reuse code. See What are traits in PHP?.
<?php
interface Logger {
    public function log($msg);
}

interface Mailer {
    public function send($to);
}

class Notifier implements Logger, Mailer {
    public function log($msg) {
        echo "Log: " . $msg . "<br>";
    }

    public function send($to) {
        echo "Mail sent to " . $to;
    }
}

$n = new Notifier();
$n->log("Notifier started");
$n->send("robin@example.com");
?>

Output:

Tutorials Class - Output Window

Log: Notifier started
Mail sent to robin@example.com

Multilevel inheritance (C extends B, and B extends A) is supported, only multiple parents at same time is not.

How to check if a file exists in PHP?

Use the file_exists() function. It takes the file name or path and returns true if it exists, otherwise false.

<?php
$file = "data.txt";

if (file_exists($file)) {
    echo "File found";
} else {
    echo "File not found";
}
?>

Output:

If data.txt is not in the folder

File not found

Note that file_exists() also returns true for folders. Use is_file() to check only files and is_dir() to check only folders.

What is the meaning of final class and final method in PHP?

The final keyword is used to stop inheritance. If a class is marked final, no other class can extend it. If a method is marked final, child classes can not override it.

<?php
class Base {
    final public function show() {
        echo "This method can not be changed";
    }
}

class Child extends Base {
    // Writing show() here would give a fatal error
}

$c = new Child();
$c->show();
?>

Output:

Tutorials Class - Output Window

This method can not be changed

A final class is written like this:

<?php
final class Util {
    public static function version() {
        return "1.0";
    }
}

// class Other extends Util {}  // Fatal error: a final class can not be extended
?>

When to use it: when a class or method must not be changed, for example a security check or a core logic. Note that properties can not be final, but from PHP 8.1 you can use readonly for properties that must not change after setting.

How to get the size of a file in PHP?

Use the filesize() function. It returns the size of a file in bytes. If the file does not exist, it gives a warning and returns false.

<?php
file_put_contents("sample.txt", "Hello PHP");

echo filesize("sample.txt") . " bytes";
?>

Output:

Tutorials Class - Output Window

9 bytes

To show the size in KB, divide it by 1024.

<?php
$kb = filesize("sample.txt") / 1024;

echo round($kb, 2) . " KB";
?>

Output:

Tutorials Class - Output Window

0.01 KB

PHP remembers the result of filesize() for the same file. If the file changes during the same script, call clearstatcache() first.

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

Both abstract class and interface are used to force child classes to follow a structure. But they are used for different purposes.

An abstract class is a partly built class. It can have normal methods with code and abstract methods without code. An interface is only a contract: it lists the methods that a class must have.

FeatureAbstract classInterface
Keywordabstract class and extendsinterface and implements
Method with codeYesNo, only method names
PropertiesYesNo (only constants)
InheritanceA class can extend only oneA class can implement many
Method visibilitypublic, protected or privatepublic only
Best used forSharing common code between related classesGiving same rules to unrelated classes
<?php
abstract class Shape {
    abstract public function area();

    public function describe() {
        return "Area is " . $this->area();
    }
}

class Square extends Shape {
    private $side;

    public function __construct($side) {
        $this->side = $side;
    }

    public function area() {
        return $this->side * $this->side;
    }
}

$sq = new Square(4);
echo $sq->describe();
?>

Output:

Tutorials Class - Output Window

Area is 16

You can not create an object of an abstract class or an interface directly. Only the child class that completes all methods can be used to create objects.

What is the difference between include() and require() in PHP?

Both include and require add the code of another file into your script. The difference is what happens when the file is missing.

StatementIf the file is missing
includeShows a warning and the script continues
include_onceSame as include, but does not add the same file again
requireShows a fatal error and the script stops
require_onceSame as require, but does not add the same file again
<?php
echo "Start<br>";

include "missing.php";   // warning, but the script goes on
echo "After include<br>";

require "missing.php";   // fatal error, the script stops here
echo "After require";    // this line never runs
?>

What you will see: “Start”, then a warning, then “After include”, and then a fatal error. The text “After require” is never shown.

Use require for files that your page can not work without, like database connection or config. Use include for optional parts, like a sidebar. Read more in PHP File Inclusion.