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.
What are traits in PHP?
A trait is a group of methods that you can reuse in many classes. It is a way to share code between classes that are not related, and it helps to solve the problem of no multiple inheritance in PHP.
You create a trait with the trait keyword and add it to a class using the use keyword.
<?php
trait Hello {
public function sayHello() {
echo "Hello ";
}
}
trait World {
public function sayWorld() {
echo "World";
}
}
class Greeting {
use Hello, World;
}
$g = new Greeting();
$g->sayHello();
$g->sayWorld();
?>
Output:
Hello World
- A class can use many traits.
- You can not create an object of a trait directly.
- If two traits have a method with the same name, PHP gives an error. You can solve it with the
insteadofkeyword.
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:
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:
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:
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:
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().
What is the use of the static keyword in PHP?
The static keyword has two main uses in PHP: inside classes, and inside functions.
1. Static property and method. They belong to the class itself, not to an object. You can use them without creating an object, with the double colon (::).
<?php
class Counter {
public static $count = 0;
public static function increase() {
self::$count++;
}
}
Counter::increase();
Counter::increase();
echo Counter::$count;
?>
Output:
2
2. Static variable in a function. A normal variable is deleted when the function ends. A static variable keeps its value between function calls.
<?php
function visit() {
static $n = 0;
$n++;
echo $n . " ";
}
visit();
visit();
visit();
?>
Output:
1 2 3
Remember that a static method can not use $this, because there is no object.
What is the difference between $this, self and static in PHP?
These three keywords are used inside a class, but they point to different things.
| Keyword | What it means | Used for |
|---|---|---|
| $this | The current object | Normal properties and methods |
| self | The class where the code is written | Static properties, constants and static methods |
| static | The class that was actually called (late static binding) | Static methods when child classes are involved |
<?php
class Car {
public $name = "Swift";
public static $wheels = 4;
public function show() {
return $this->name . " has " . self::$wheels . " wheels";
}
}
$car = new Car();
echo $car->show();
?>
Output:
Swift has 4 wheels
The difference between self and static is seen when a child class calls the method.
<?php
class A {
public static function create() {
return new static(); // self would always create class A
}
}
class B extends A {}
echo get_class(B::create());
?>
Output:
B
If we had written new self(), the output would be A.
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:
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:
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].
What are magic methods in PHP?
Magic methods are special methods in PHP classes. Their names start with a double underscore (__). PHP calls them automatically in some situations, you do not call them yourself.
| Method | When PHP calls it |
|---|---|
| __construct() | When an object is created |
| __destruct() | When an object is destroyed |
| __get($name) | When reading a property that is not accessible or does not exist |
| __set($name, $value) | When writing to a property that is not accessible or does not exist |
| __call($name, $args) | When calling a method that does not exist |
| __toString() | When an object is used as a string, for example with echo |
| __invoke() | When an object is called like a function |
<?php
class User {
private $data = ["name" => "Robin"];
public function __get($key) {
return $this->data[$key] ?? "Not found";
}
public function __toString() {
return "User: " . $this->data["name"];
}
}
$u = new User();
echo $u->name . "<br>";
echo $u->city . "<br>";
echo $u;
?>
Output:
Robin
Not found
User: Robin
Do not create your own methods with a double underscore name, because PHP keeps these names for itself.
How to count the elements of a multidimensional array in PHP?
The count() function counts only the first level of an array. To count all elements including the inner arrays, pass COUNT_RECURSIVE as the second parameter.
<?php
$cars = [
["Volvo", 22, 18],
["BMW", 15, 13]
];
echo count($cars) . "<br>";
echo count($cars, COUNT_RECURSIVE);
?>
Output:
2
8
The first line counts the 2 inner arrays. The recursive count adds 6 inner values to them, so it is 8. The function sizeof() is only an alias of count().
What is a namespace in PHP?
A namespace is a way to group classes, functions and constants under a name. It avoids name conflicts, when two libraries have a class with the same name, for example User or Logger.
Think of it like folders on your computer. Two files can have same name if they are in different folders.
<?php
namespace App\Models;
class User {
}
// ::class gives the full name including namespace
echo User::class;
?>
Output:
App\Models\User
To use a class from another namespace, write its full name, or import it with the use keyword at the top of the file.
<?php
use App\Models\User;
$user = new User();
?>
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:
1,2,5,12
<?php
$user = ["name" => "Robin", "age" => 25];
echo json_encode($user);
?>
Output:
{“name”:”Robin”,”age”:25}
Read more about implode() in PHP implode() Function. To do the opposite, see PHP explode() Function.
What are the new features of PHP 8?
PHP 8.0 was a big release. It added many features that make code shorter and safer. Here are the main ones that are asked in interviews.
- Named arguments: pass values by parameter name, for example
new User(name: "Robin"). - Constructor property promotion: declare and set properties in the constructor line.
- Match expression: a stricter and shorter version of switch. See PHP match Expression.
- Nullsafe operator (?->): stops the chain if the value is null.
- Union types: a parameter or return can have more than one type, like
int|string. - Attributes: add metadata to classes and methods using the
#[...]syntax. - JIT compiler: can make some heavy calculations faster.
- New functions:
str_contains(),str_starts_with()andstr_ends_with().
<?php
class User {
public function __construct(public string $name, public ?string $city = null) {}
}
$user = new User(name: "Robin"); // named argument
echo $user->name . "<br>";
echo ($user?->city ?? "City not given") . "<br>"; // nullsafe operator
echo str_contains("Tutorials Class", "Class") ? "Found" : "Not found";
?>
Output:
Robin
City not given
Found
Later versions added more, for example enums and readonly properties in PHP 8.1. Always check the version of PHP on your server before using a new feature.
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:
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:
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:
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:
key1 = value1
key2 = value2
key3 = value3
How to move the internal pointer of an array in PHP?
Every PHP array has an internal pointer that points to one element. You can move it with these functions:
| Function | What it does |
|---|---|
| current() | Returns the element where the pointer is now |
| key() | Returns the key of the current element |
| next() | Moves the pointer one step forward |
| prev() | Moves the pointer one step back |
| reset() | Moves the pointer to the first element |
| end() | Moves the pointer to the last element |
<?php
$fruits = ["apple", "banana", "cherry"];
echo current($fruits) . "<br>";
echo next($fruits) . "<br>";
echo next($fruits) . "<br>";
echo prev($fruits) . "<br>";
echo reset($fruits) . "<br>";
echo end($fruits);
?>
Output:
apple
banana
cherry
banana
apple
cherry
When the pointer goes outside the array, next() and prev() return false.
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:
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:
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:
Wrong: says not found
Correct: found
Both functions are case-sensitive. Learn more in PHP strpos() Function.
What is the use of substr_count() in PHP?
The substr_count() function counts how many times a small text (substring) is found in a bigger string.
<?php
echo substr_count("hello world, hello PHP", "hello") . "<br>";
// Overlapping matches are not counted twice
echo substr_count("aaa", "aa");
?>
Output:
2
1
- It is case-sensitive. “Hello” and “hello” are different.
- It does not count overlapping matches.
- To count the words of a string use
str_word_count(), and to count array elements usecount().
What is the difference between strlen() and mb_strlen() in PHP?
strlen() returns the length of a string in bytes. mb_strlen() returns the length in characters. For English letters both are same, but for other languages they are different, because one character can use many bytes.
<?php
$english = "PHP";
$hindi = "नमस्ते";
echo strlen($english) . "<br>";
echo strlen($hindi) . "<br>";
echo mb_strlen($hindi, "UTF-8");
?>
Output:
3
18
6
The Hindi word has 6 characters, but it takes 18 bytes in UTF-8. So use mb_strlen() whenever the text can have non-English letters, emoji or accents. It needs the mbstring extension, which is enabled in most servers.
What is the use of strip_tags() in PHP?
The strip_tags() function removes HTML and PHP tags from a string. Only the tags are removed, the text inside them stays.
<?php
echo strip_tags("<b>Hello</b> <i>PHP</i>");
?>
Output:
Hello PHP
You can keep some tags by passing them as second parameter. Here we allow only the bold tag, and we use htmlspecialchars() just to show the HTML code as text.
<?php
$text = "<p><b>Hello</b> <i>PHP</i></p>";
echo htmlspecialchars(strip_tags($text, "<b>"));
?>
Output:
<b>Hello</b> PHP
What is the difference between strstr() and stristr() in PHP?
Both functions find the first match of a text inside a string and return the part of the string from that match to the end. The difference is that strstr() is case-sensitive, and stristr() is case-insensitive (it ignores upper or lower case).
<?php
$email = "sonia@example.com";
echo strstr($email, "@") . "<br>";
echo strstr($email, "@", true) . "<br>";
var_dump(strstr("Hello World", "world"));
echo stristr("Hello World", "world");
?>
Output:
@example.com
sonia
bool(false)
World
The third parameter true returns the part before the match. If there is no match, both functions return false. When you only want to know if a text exists, str_contains() is simpler.