PHP Interview Questions & Answers for Freshers

PHP interview questions for freshers: what PHP is, data types, variables, operators, strings, arrays, include vs require, GET vs POST, cookies, sessions and file 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.

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 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.

What is a constructor in PHP?

A constructor is a special method that runs automatically when an object is created. In PHP it is written as __construct(). It is mostly used to set the starting values of the object.

A destructor, written as __destruct(), is the opposite. It runs when the object is destroyed, or when the script ends.

<?php
class Student {
    public $name;

    public function __construct($name) {
        $this->name = $name;
        echo "Object created for " . $name . "<br>";
    }

    public function __destruct() {
        echo "Object for " . $this->name . " is destroyed";
    }
}

$s = new Student("Robin");
echo "Script is running...<br>";
?>

Output:

Tutorials Class - Output Window

Object created for Robin
Script is running…
Object for Robin is destroyed

From PHP 8.0 you can write a shorter constructor using constructor property promotion. The property is declared and set in the constructor line itself.

<?php
class Student {
    public function __construct(public string $name) {}
}

$s = new Student("Robin");
echo $s->name;
?>

Output:

Tutorials Class - Output Window

Robin

How to count the number of words in a string in PHP?

Use the str_word_count() function. It returns how many words are in a string.

<?php
echo str_word_count("Hello world, welcome to Tutorials Class");
?>

Output:

Tutorials Class - Output Window

6

If you pass 1 as the second parameter, it returns the words in an array instead of the count.

<?php
$words = str_word_count("Learn PHP today", 1);

print_r($words);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => Learn
[1] => PHP
[2] => today
)

str_word_count() counts only letters, so numbers are not counted as words, and it does not work well for non-English text. For such text, use count(explode(" ", $text)) or preg_split().

How to merge two or more arrays in PHP?

Use the array_merge() function to merge two or more arrays into one new array. You can also use the + operator, but it works in a different way.

<?php
$a = [1, 2];
$b = [3, 4];
$c = [5, 6];

print_r(array_merge($a, $b, $c));
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => 1
[1] => 2
[2] => 3
[3] => 4
[4] => 5
[5] => 6
)

array_merge() vs + operator. When two arrays have the same string key, array_merge() keeps the later value, but the + operator keeps the first value.

<?php
$x = ["a" => "Apple", "b" => "Banana"];
$y = ["b" => "Blueberry", "c" => "Cherry"];

print_r(array_merge($x, $y));
print_r($x + $y);
?>

Output:

Tutorials Class - Output Window

Array
(
[a] => Apple
[b] => Blueberry
[c] => Cherry
)
Array
(
[a] => Apple
[b] => Banana
[c] => Cherry
)

For numeric keys, array_merge() renumbers the keys from 0, while + keeps the keys and skips the ones that already exist. From PHP 7.4 you can also merge with the spread operator, like [...$a, ...$b].

How to convert an array to a string in PHP?

Use the implode() function to join the values of an array into a string. If you need the complete array with keys, use json_encode().

<?php
$numbers = [1, 2, 5, 12];

echo implode(",", $numbers);
?>

Output:

Tutorials Class - Output Window

1,2,5,12

<?php
$user = ["name" => "Robin", "age" => 25];

echo json_encode($user);
?>

Output:

Tutorials Class - Output Window

{“name”:”Robin”,”age”:25}

Note: If you try echo $array directly, PHP prints the word “Array” and gives a warning “Array to string conversion”. Use one of the functions above instead.

Read more about implode() in PHP implode() Function. To do the opposite, see PHP explode() Function.

How to remove duplicate values from an array in PHP?

Use the array_unique() function. It removes the duplicate values and keeps only the first one. The keys of the remaining values are not changed.

<?php
$fruits = ["a" => "apple", "b" => "banana", "c" => "apple"];

print_r(array_unique($fruits));
?>

Output:

Tutorials Class - Output Window

Array
(
[a] => apple
[b] => banana
)

For a normal numeric array, you will see gaps in the keys after removing duplicates. Use array_values() to reindex it from 0.

<?php
$numbers = [1, 2, 2, 3, 1];

print_r(array_values(array_unique($numbers)));
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => 1
[1] => 2
[2] => 3
)

By default array_unique() compares values as strings, so "1" and 1 are treated as same value.

How to get keys and values separately from an associative array in PHP?

Use array_keys() to get all the keys and array_values() to get all the values of an associative array. Both return a new array.

<?php
$data = ["key1" => "value1", "key2" => "value2", "key3" => "value3"];

print_r(array_keys($data));
print_r(array_values($data));
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => key1
[1] => key2
[2] => key3
)
Array
(
[0] => value1
[1] => value2
[2] => value3
)

If you need both together, use a foreach loop with the key and value.

<?php
$data = ["key1" => "value1", "key2" => "value2", "key3" => "value3"];

foreach ($data as $key => $value) {
    echo $key . " = " . $value . "<br>";
}
?>

Output:

Tutorials Class - Output Window

key1 = value1
key2 = value2
key3 = value3

How to replace a part of a string in PHP?

Use the str_replace() function. It replaces all matches of a search text with a new text. The syntax is str_replace(search, replace, subject).

<?php
echo str_replace("world", "Dolly", "Hello world!") . "<br>";

// Count how many replacements were done
$text = str_replace("a", "A", "banana", $count);
echo $text . " (" . $count . " replaced)<br>";

// Case-insensitive replace
echo str_ireplace("WORLD", "PHP", "Hello world!");
?>

Output:

Tutorials Class - Output Window

Hello Dolly!
bAnAnA (3 replaced)
Hello PHP!

str_replace() is case-sensitive, use str_ireplace() when the case does not matter. To replace only by position, use substr_replace(). Related: What is the use of str_replace()?.

How to check if a string contains a substring in PHP?

From PHP 8 use str_contains(). It returns true or false. In older versions use strpos(), which returns the position of the match or false.

<?php
$text = "Hello world!";

var_dump(str_contains($text, "world"));
var_dump(strpos($text, "Hello"));
?>

Output:

Tutorials Class - Output Window

bool(true)
int(0)

Look at the second result. The word “Hello” is at position 0, and 0 is also treated as false in a normal comparison. This is the most common mistake with strpos(), so always compare with !==.

<?php
$text = "Hello world!";

if (strpos($text, "Hello") == false) {
    echo "Wrong: says not found<br>";
}

if (strpos($text, "Hello") !== false) {
    echo "Correct: found";
}
?>

Output:

Tutorials Class - Output Window

Wrong: says not found
Correct: found

Both functions are case-sensitive. Learn more in PHP strpos() Function.