PHP Interview Questions & Answers for experienced
PHP Interview Questions & Answers for experienced are provided here. TutorialsClass helps you to test your knowledge and enhance your experience.
Read PHP Interview Questions & Answers for experienced candidates to get your dream job.
How can we submit a form without a submit button?
A form can be sent with JavaScript, without a submit button. Use the submit() method of the form, for example from a link click or when a select box changes.
<form id="myForm" method="post" action="process.php">
<input type="text" name="name" value="Robin">
</form>
<a href="#" onclick="document.getElementById('myForm').submit(); return false;">Send the form</a>
<select onchange="this.form.submit()" name="city" form="myForm">
<option>Delhi</option>
<option>Mumbai</option>
</select>
PHP receives the data in the normal way, from $_POST. See PHP Forms Handling.
What is PHP floor() function?
The floor() function rounds a number down to the next lower whole number. It always returns a float.
<?php
echo floor(7.8) . "<br>";
echo floor(-3.2) . "<br>";
var_dump(floor(5.9));
?>
Output:
7
-4
float(5)
Notice that floor(-3.2) is -4, because -4 is lower than -3.2. The related functions are ceil() (round up) and round() (round to the nearest). Use intdiv() for whole number division.
What is the difference between mysqli_fetch_array() and mysqli_fetch_object()?
Both functions read one row from a MySQL result, but the format of the row is different.
| Function | Returns the row as | How to read a value |
|---|---|---|
| mysqli_fetch_array() | An array with both numeric and column-name keys | $row["name"] or $row[0] |
| mysqli_fetch_object() | An object, columns are properties | $obj->name |
| mysqli_fetch_assoc() | An array with column-name keys only | $row["name"] |
The examples use the users table of our MySQL chapters. Suppose the user with id 1 is Ram.
<?php
require_once('db-connection.php');
$sql = "SELECT name, email FROM users WHERE id = 1";
$row = mysqli_fetch_array(mysqli_query($conn, $sql));
echo $row["name"] . " / " . $row[1] . "<br>";
$obj = mysqli_fetch_object(mysqli_query($conn, $sql));
echo $obj->name . " / " . $obj->email;
?>
Output:
Ram / ram@example.com
Ram / ram@example.com
In the first line, $row[1] is the second column (email), because the numeric keys start from 0. Most developers prefer mysqli_fetch_assoc(), because it does not keep every value two times. See all the options in ways to fetch data from a result set.
How can you pass a variable by reference in PHP?
Write an ampersand (&) before the parameter in the function. Then the function works on the original variable, not on a copy.
Normally PHP passes arguments by value. If the function changes the value, the variable outside does not change. With a reference it does.
<?php
function add_line(&$line) {
$line .= " and extra words added.";
}
$sample = "This is a sample line,";
add_line($sample);
echo $sample;
?>
Output:
This is a sample line, and extra words added.
Without the &, the output would be only “This is a sample line,”. Objects are different: PHP passes the handle of an object, so a function can change its properties without any ampersand.
How to force a maximum execution time error in PHP?
To test this error, set a small time limit with set_time_limit() and run a loop that keeps PHP busy, so the script crosses the limit.
<?php
set_time_limit(2); // allow only 2 seconds
while (true) {
// busy loop, never stops
}
?>
Output:
Fatal error: Maximum execution time of 2 seconds exceeded in /path/index.php on line 5
To remove the limit, see how to set infinite execution time, and to change the default see how to increase maximum execution time.
How to increase maximum execution time in PHP and WordPress?
A long job (an import, a big backup or a slow plugin) can stop with Maximum execution time exceeded. The limit is set by the PHP setting max_execution_time (in seconds). Ways to raise it:
- php.ini:
max_execution_time = 300 - .htaccess (Apache with mod_php):
php_value max_execution_time 300 - In code: call
set_time_limit( 300 );orini_set( 'max_execution_time', '300' );before the long job. - Your host panel: many hosts have a PHP settings page.
Here we check the value on a real page, before and after calling set_time_limit() from a small must use plugin:
<?php
add_action( 'wp_footer', function () {
echo '<!-- before: ' . ini_get( 'max_execution_time' ) . ' -->';
set_time_limit( 300 );
echo '<!-- after: ' . ini_get( 'max_execution_time' ) . ' -->';
} );
$ curl -s http://example.com/ | grep -o "<!– \(before\|after\): [0-9]* –>"
<!– before: 30 –>
<!– after: 300 –>
WP-CLI scripts have no time limit by default, which is why long jobs are often done with it. Some hosts block set_time_limit(), and a web server (Nginx or a proxy) can have its own timeout too. Do not set it too high on a live site.
How to Fix Incorrect format parameter error when importing large database in PHPMyAdmin?
This error appears when you import a big SQL file in phpMyAdmin. It is usually not a problem with the file, but with the limits of PHP on your server.
Common causes:
- The file is bigger than
upload_max_filesizeorpost_max_size. - The import takes longer than
max_execution_time. - The script needs more memory than
memory_limitallows.
Fix 1: compress the SQL file. phpMyAdmin can import a .zip or .gz file directly, and it is much smaller.
Fix 2: increase the limits in php.ini (or .user.ini), then restart the server.
upload_max_filesize = 256M
post_max_size = 256M
memory_limit = 512M
max_execution_time = 600
See how to increase the upload size and the execution time.
Fix 3: remove the phpMyAdmin time limit by adding this line in its config.inc.php file.
$cfg['ExecTimeLimit'] = 0;
Fix 4: import with the command line. This is the best way for very big files, because PHP limits do not apply.
mysql -u username -p database_name < backup.sql
What is the difference between $var and $$var in PHP?
$var is a normal variable. $$var is called a variable variable. PHP takes the value stored in $var and uses it as the name of another variable.
<?php
$var = "city";
$$var = "Delhi"; // same as $city = "Delhi";
echo $var . "<br>";
echo $$var . "<br>";
echo $city;
?>
Output:
city
Delhi
Delhi
Variable variables are hard to read and debug, so use them rarely. In most cases an array is a better choice. See PHP Variables for the basics.
What is the null coalescing operator (??) in PHP?
The null coalescing operator (??) returns the left value if it exists and is not NULL, otherwise it returns the right value. It is a short form of isset() with a ternary operator, and it never gives an “undefined” warning.
<?php
$user = ["name" => "Robin"];
echo $user["city"] ?? "Not given";
echo "<br>";
echo $user["name"] ?? "Not given";
?>
Output:
Not given
Robin
From PHP 7.4 you can also use ??=. It sets the value only when the variable is not set or is NULL.
<?php
$settings = [];
$settings["theme"] ??= "light";
echo $settings["theme"];
?>
Output:
light
It is very useful with $_GET and $_POST, for example $page = $_GET["page"] ?? 1;. See also PHP isset().
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:
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.
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.
| Feature | Abstract class | Interface |
|---|---|---|
| Keyword | abstract class and extends | interface and implements |
| Method with code | Yes | No, only method names |
| Properties | Yes | No (only constants) |
| Inheritance | A class can extend only one | A class can implement many |
| Method visibility | public, protected or private | public only |
| Best used for | Sharing common code between related classes | Giving 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:
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 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 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.
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();
?>
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 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.
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.