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.

Note: Do not name any form field “submit” or “action”. It hides the form method and submit() stops working. Also remember that submit() skips the HTML validation, use requestSubmit() if you want the browser to check the fields first.

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:

Tutorials Class - Output Window

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.

FunctionReturns the row asHow 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:

Tutorials Class - Output Window

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:

Tutorials Class - Output Window

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.

Note: Use references only when you really need them, because they make the code harder to follow. Often it is cleaner to return the new value from the function. See PHP Functions.

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:

Sample message, the path will be different

Fatal error: Maximum execution time of 2 seconds exceeded in /path/index.php on line 5

Note: Many people try sleep(10), but on Linux and macOS the execution time counts only the time PHP really works (CPU time), not the time it sleeps. So sleep() will not give this error there. On Windows the sleeping time is counted.

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:

  1. php.ini: max_execution_time = 300
  2. .htaccess (Apache with mod_php): php_value max_execution_time 300
  3. In code: call set_time_limit( 300 ); or ini_set( 'max_execution_time', '300' ); before the long job.
  4. 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' ) . ' -->';
} );
Terminal output

$ 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_filesize or post_max_size.
  • The import takes longer than max_execution_time.
  • The script needs more memory than memory_limit allows.

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
Note: Take a backup before you import into a database that already has data, because an import can overwrite tables. Splitting a big file into smaller parts also works.

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:

Tutorials Class - Output Window

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:

Tutorials Class - Output Window

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:

Tutorials Class - Output Window

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:

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.

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

Tutorials Class - Output Window

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

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:

Tutorials Class - Output Window

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:

Tutorials Class - Output Window

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.

KeywordWhat it meansUsed for
$thisThe current objectNormal properties and methods
selfThe class where the code is writtenStatic properties, constants and static methods
staticThe 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:

Tutorials Class - Output Window

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:

Tutorials Class - Output Window

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.

MethodWhen 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:

Tutorials Class - Output Window

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:

Tutorials Class - Output Window

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:

Tutorials Class - Output Window

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();
?>
Note: The namespace line must be the first statement in the file, only declare can come before it.

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() and str_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:

Tutorials Class - Output Window

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:

FunctionWhat 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:

Tutorials Class - Output Window

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:

Tutorials Class - Output Window

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.