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.

How to terminate or break a loop in PHP?

Use the break keyword inside a loop to stop it immediately. The code after the loop continues to run. It works in for, while, do...while, foreach and switch.

<?php
for ($i = 1; $i <= 10; $i++) {
    if ($i == 4) {
        break;      // stop the loop
    }
    echo $i . " ";
}
echo "<br>Loop ended";
?>

Output:

Tutorials Class - Output Window

1 2 3
Loop ended

In nested loops, break 2 stops two levels of loops at once. If you only want to skip one round and go to the next one, use continue. Both are explained in PHP Loops.

What is single line comment in PHP? Explain with syntax.

A single line comment tells PHP to ignore everything on that line after the comment symbol. In PHP you can start it with // or #. You do not need to close it.

<?php
// This is a single line comment
# This is also a single line comment

echo "Hello World!";   // comment after the code
?>

Output:

Tutorials Class - Output Window

Hello World!

The comment ends at the end of the line (or at the closing ?> tag). For many lines use /* ... */. In PHP 8 the text #[ starts an attribute, so write a space after the hash. See all types of comments in PHP Comments.

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 can we set infinite execution time in a PHP script?

Add set_time_limit(0) at the beginning of the script. Zero means no time limit. You can also use ini_set("max_execution_time", 0).

<?php
set_time_limit(0);   // no time limit for this script

// long running job here
?>
  • It works only if your hosting allows it. Some hosts disable set_time_limit() or force a limit.
  • The web server can still stop the request: Apache has Timeout, Nginx has fastcgi_read_timeout, and some hosts have a proxy limit.
  • In the command line (CLI) the default is already 0, so a long script runs without limit.
Note: A web page that runs for many minutes is a bad idea, because the visitor is waiting and can close the page. Run long jobs in the background (a cron job or a queue) and show the progress. To only increase the limit, 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.

What is the difference between == and === Operators in PHP?

== (equal) compares only the values, and PHP may change the data type before comparing. === (identical) compares the value and the data type, so it is strict.

<?php
$num_1 = 12;      // integer
$num_2 = "12";    // string

var_dump($num_1 == $num_2);
var_dump($num_1 === $num_2);
var_dump(0 == "abc");
var_dump(null == false);
var_dump(null === false);
?>

Output:

Output in PHP 8

bool(true)
bool(false)
bool(false)
bool(true)
bool(false)

  • The first comparison is true because the values are same, but the second is false because one is an integer and the other is a string.
  • 0 == "abc" was true in PHP 7, but PHP 8 changed it to false.
  • null == false is true, because both are false-like. With === it is false.

Use === in your conditions. The opposite operators are != and !==, see != vs !==. All operators are in PHP Operators.

What is the difference between GET and POST method in PHP?

GET and POST are two HTTP methods that a browser uses to send data to the server. PHP reads them with $_GET and $_POST.

GETPOST
Where is the dataIn the URL, after the question markIn the body of the request
Visible in the URLYesNo
Data lengthLimited by the URL length (browsers allow about 2000 characters)Large, limited by post_max_size
Bookmark and sharePossibleNot possible
Cached by the browserYesNo
Use forReading and searching data: search, filters, page numbersSending data that changes something: login, registration, files
Safe to repeatYesNo, the browser asks before sending again

GET example. The data is in the URL, like index.php?name=Robin&age=25.

<?php
// URL: index.php?name=Robin&age=25
$name = $_GET["name"] ?? "Guest";
$age = $_GET["age"] ?? "unknown";

echo $name . " is " . $age;
?>

Output:

For the URL above

Robin is 25

POST example. The values are not in the URL.

<form method="post" action="login.php">
    <input type="text" name="username">
    <input type="password" name="password">
    <button type="submit">Login</button>
</form>
<?php
// login.php
$username = $_POST["username"] ?? "";

echo "Hello " . htmlspecialchars($username);
?>
Note: POST is not secret by itself. The data is still visible to anyone who can see the network. Use HTTPS, and never send passwords with GET, because URLs are saved in the browser history and in server logs. Validate all data in both cases, see PHP Forms Handling and PHP Security Tips.

How do you split a string into an array?

Use explode() to split a string into an array at a separator, like a comma. Here the extra spaces after the commas are removed with trim().

<?php
$languages = "PHP, HTML, CSS, JavaScript, MySQL";

$list = array_map("trim", explode(",", $languages));

print_r($list);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => PHP
[1] => HTML
[2] => CSS
[3] => JavaScript
[4] => MySQL
)

To split a string into single characters use str_split(). To split by a pattern (like many spaces) use preg_split().

<?php
echo json_encode(str_split("PHP")) . "<br>";
echo json_encode(preg_split("/\s+/", "one   two three"));
?>

Output:

Tutorials Class - Output Window

[“P”,”H”,”P”]
[“one”,”two”,”three”]

Learn more in PHP explode() Function.

How to Change Time Zone Settings in PHP?

On most servers the default time zone of PHP is UTC. To change it for all date and time functions, use date_default_timezone_set(), at the beginning of your script.

<?php
date_default_timezone_set("Asia/Kolkata");

echo date_default_timezone_get();
?>

Output:

Tutorials Class - Output Window

Asia/Kolkata

To change it for the whole server, set it in php.ini:

date.timezone = "Asia/Kolkata"

With the DateTime class you can show one moment in different zones.

<?php
$d = new DateTime("2026-06-01 12:00:00", new DateTimeZone("UTC"));
echo $d->format("H:i") . " UTC<br>";

$d->setTimezone(new DateTimeZone("Asia/Kolkata"));
echo $d->format("H:i") . " India";
?>

Output:

Tutorials Class - Output Window

12:00 UTC
17:30 India

The names of all time zones are on php.net, in the list of supported time zones. See also PHP Date and Time.

How to Get the Current Year using PHP?

Use the built-in date() function with the format character Y. It gives the current year with 4 digits.

<?php
echo date("Y");
?>

Output:

Output in the year 2026

2026

The most common use is the copyright line in the footer, so you do not have to change it every year.

<footer>
    &copy; <?php echo date("Y"); ?> Tutorials Class
</footer>

The year comes from the server time and its time zone. Near midnight of 31 December it can be different for some visitors, see how to change the time zone. The same with the DateTime class: (new DateTime())->format("Y"). More in PHP Date and Time.

What is fopen function PHP?

fopen() opens a file (or a URL) and returns a file handle, that you use with functions like fgets(), fwrite() and fclose(). If it fails, it returns false and shows a warning.

<?php
$handle = fopen("sample.txt", "r");

if ($handle === false) {
    die("Could not open the file.");
}

echo fgets($handle);   // read the first line

fclose($handle);
?>

Output:

Tutorials Class - Output Window

Line 1

The second parameter is the mode: r read, w write (erases the file), a append, x create a new file. See the full table in PHP File Handling. Always close the file with fclose().

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 are the arithmetic operators in PHP?

Arithmetic operators are used to do maths on numbers. PHP has these arithmetic operators:

OperatorNameExampleResult
+Addition10 + 313
–Subtraction10 – 37
*Multiplication10 * 330
/Division10 / 33.3333333333333
%Modulus (remainder)10 % 31
**Exponentiation (power)10 ** 31000
<?php
$a = 10;
$b = 3;

echo ($a + $b) . "<br>";
echo ($a - $b) . "<br>";
echo ($a * $b) . "<br>";
echo ($a / $b) . "<br>";
echo ($a % $b) . "<br>";
echo ($a ** $b);
?>

Output:

Tutorials Class - Output Window

13
7
30
3.3333333333333
1
1000

Division always gives a float when the result is not a whole number. Use intdiv() if you need only the whole part. Read all operators in PHP Operators.

What is the use of the ternary operator in PHP?

The ternary operator is a short way to write a simple if-else statement in one line. The syntax is condition ? value_if_true : value_if_false.

<?php
$age = 20;

$result = ($age >= 18) ? "Adult" : "Minor";

echo $result;
?>

Output:

Tutorials Class - Output Window

Adult

There is also a shorter form ?: (called Elvis operator). It returns the first value if it is not empty, otherwise the second one.

<?php
$username = "";

echo $username ?: "Guest";
?>

Output:

Tutorials Class - Output Window

Guest

Use it only for short and simple conditions. For long conditions a normal if-else is easier to read. More details in PHP Ternary Operator.

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 difference between division (/) and modulus (%) in PHP?

The division operator (/) gives the result of dividing one number by another. The modulus operator (%) gives only the remainder of that division.

<?php
$a = 10;
$b = 3;

echo $a / $b . "<br>";        // division
echo $a % $b . "<br>";        // modulus (remainder)
echo intdiv($a, $b);          // whole number part only
?>

Output:

Tutorials Class - Output Window

3.3333333333333
1
3

Modulus is often used to check even or odd numbers. If $number % 2 is 0, the number is even.

Note: In PHP 8, dividing or using modulus with zero throws a DivisionByZeroError. Check the divisor before the calculation.

What is the difference between != and !== in PHP?

!= (not equal) checks only the value. !== (not identical) checks the value and the data type. So !== is more strict.

<?php
$a = 5;       // integer
$b = "5";     // string

var_dump($a != $b);    // values are same, so false
var_dump($a !== $b);   // data types are different, so true
?>

Output:

Tutorials Class - Output Window

bool(false)
bool(true)

In PHP, <> works same as !=. The same logic applies to the opposite operators, see difference between == and ===.

What is the difference between $var++ and $var + 1 in PHP?

$var + 1 only calculates a new value and does not change $var. $var++ is the increment operator, it changes the value of $var by adding 1.

There is one more thing to remember. $var++ (post-increment) returns the old value first and then increases. ++$var (pre-increment) increases first and then returns the new value.

<?php
$a = 5;
$b = $a + 1;      // $a is not changed
echo $a . " " . $b . "<br>";

$x = 5;
$y = $x++;        // $y gets old value 5, then $x becomes 6
echo $x . " " . $y . "<br>";

$m = 5;
$n = ++$m;        // $m becomes 6 first, then $n gets 6
echo $m . " " . $n;
?>

Output:

Tutorials Class - Output Window

5 6
6 5
6 6

Which special characters are allowed in PHP variable names?

Only the underscore (_) is allowed as a special character in a PHP variable name. Characters like -, @, # and a space are not allowed.

Here are the full rules:

  • A variable name starts with the dollar sign $.
  • After the dollar sign, the first character must be a letter or an underscore, not a digit.
  • The rest of the name can have letters, digits and underscores.
  • Variable names are case-sensitive. $name and $Name are two different variables.
Variable nameValid?
$nameYes
$_nameYes
$user_name2Yes
$2nameNo, starts with a digit
$first-nameNo, hyphen is not allowed
$first nameNo, space is not allowed

PHP also accepts some non-English letters, but it is better to use only a to z in names. Read more in PHP Variables.