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 check if a variable is empty in PHP?

Use the empty() function. It returns true when the variable does not exist or has a false-like value, and false otherwise.

<?php
$a = "";
$b = "0";
$c = "Hello";

var_dump(empty($a));
var_dump(empty($b));
var_dump(empty($c));
?>

Output:

Tutorials Class - Output Window

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

These values are all empty: "", 0, 0.0, "0", null, false, [] and an undefined variable. The string “0” is a surprise for many people, so do not use empty() when 0 is a valid value.

Read the full chapter PHP empty() and the comparison isset() vs empty() vs is_null().

What is PHP?

PHP (PHP: Hypertext Preprocessor) is a popular, free and open-source server-side scripting language. It is mostly used to create websites and web applications. PHP code runs on the server, and the visitor gets only the result as HTML.

With PHP you can create static and dynamic websites, handle forms, work with cookies and sessions, send emails, read and write files, and connect with databases like MySQL.

<?php
echo "Hello, World!";
?>

Output:

Tutorials Class - Output Window

Hello, World!

PHP powers WordPress and many other big websites. The current series is PHP 8. Start learning in the PHP Introduction, and see the full form of PHP also.

Who is the father of PHP?

Rasmus Lerdorf is known as the father of PHP. He created it in 1994 as a set of small CGI programs, written in the C language, to track the visitors of his online resume. The first public release came in 1995.

In 1997 two developers, Zeev Suraski and Andi Gutmans, rewrote the core of the language. Their work became PHP 3, and later they built the Zend Engine (the name comes from the first letters of Zeev and Andi) that is the base of PHP from PHP 4 until today.

Read more in the PHP Introduction.

What is the correct & common way to start and finish a PHP block of code?

The correct and recommended way is the standard tags: <?php to start and ?> to finish.

<?php
echo "Hello from standard tags";
?>

Output:

Tutorials Class - Output Window

Hello from standard tags

There is also the short echo tag <?= ... ?>. It prints a value and it is always available (PHP 5.4 and above), so it is good inside HTML.

<p>Year: <?= date("Y") ?></p>
  • The old short open tag <? ... ?> works only when short_open_tag is On in php.ini. It is usually Off, so do not use it.
  • In a file that has only PHP code, leave out the closing ?> tag. It avoids problems with extra spaces after it.

See also PHP Syntax.

What is Open Source Software?

Open source software is software whose source code is made available to everyone. Anyone can see the code, use the software, change it, and share it with others, under the rules of its license.

Examples: PHP, MySQL, WordPress, Linux, Apache and Git.

  • Free to start: most open source tools do not cost anything.
  • Safer and better: many people check the code and find the bugs.
  • No lock-in: you can change the software or move your data when you want.
  • Big community: you get help, plugins and tutorials easily.
Note: Open source does not always mean free of cost for every use, and every project has a license (like GPL or MIT) with rules. Read the license before you use or sell something built with it.

Is PHP a case sensitive language?

Partly. In PHP, variable names are case-sensitive, but function names, class names and keywords are not.

Case-sensitiveNot case-sensitive
Variable names ($name and $Name are different)Keywords like echo, if, while, function
Constants (created with define or const)Function names (sum() and SUM() are same)
Array keys (“Name” and “name” are different)Class names and method names
<?php
$name = "James";

ECHO $name . "<br>";     // keywords are not case-sensitive

function sum() {
    return "Function called";
}

echo SUM();              // same as sum()
?>

Output:

Tutorials Class - Output Window

James
Function called

If you write echo $NAME;, PHP shows a warning “Undefined variable $NAME”, because it is a different variable.

Note: Even if PHP allows it, write function and class names in the same case as they were created. It keeps the code clean. See PHP Syntax.

What is the default extension of the PHP file?

The default extension of a PHP file is .php, for example index.php. The web server sends every file with this extension to PHP, which runs the code and sends the result to the browser.

You may see .phtml or .php5 in some old projects, but today .php is used everywhere.

Note: Never save PHP files like config or include files as .inc or .txt. The server does not run them, so a visitor can open them in the browser and read your code and passwords. Always use .php.

What are the different data types in PHP?

The PHP manual lists ten primitive data types in three groups.

GroupTypeExample
Scalarstring“Hello PHP!”
Scalarinteger2567
Scalarfloat (double)1.5 or 134.153
Scalarbooleantrue or false
Compoundarray[1, 2, 3]
CompoundobjectAn instance of a class
CompoundcallableA function that can be called
CompounditerableAn array or an object that can be looped
SpecialNULLA variable with no value
SpecialresourceA reference to an outside thing, like an open file

In PHP you do not write the type when you create a variable. PHP picks it from the value. You can check it with var_dump() or gettype(). Learn all of them with examples in PHP Data Types.

What is PHP Function?

A function is a block of statements that does one specific job. It can take values as input (parameters), do some work and give back a result. You write it once and call it whenever you need.

<?php
function add($a, $b) {
    return $a + $b;
}

echo add(5, 3);
?>

Output:

Tutorials Class - Output Window

8

PHP has many built-in functions (like strlen()) and you can also create your own with the function keyword. Learn more in PHP Functions.

What are the form method Attribute available for submitting?

The method attribute of the HTML <form> tag tells how the form data is sent to the server. There are two values: GET and POST. If you write nothing, the default is GET.

<form method="get" action="search.php">
    <!-- fields -->
</form>

<form method="post" action="login.php">
    <!-- fields -->
</form>
GETPOST
Data goes in the URL (visible)Data goes in the request body (not in the URL)
PHP reads it from $_GETPHP reads it from $_POST
Use for search and filtersUse for login, registration and changes

The details are in difference between GET and POST and PHP Forms Handling.

What are the different PHP functions to sort an array?

PHP has many functions to sort an array. Choose one by asking: do you sort by value or by key, in which order, and do you need to keep the keys?

FunctionSortsKeeps keys?
sort()Values, low to highNo
rsort()Values, high to lowNo
asort()Values, low to highYes
arsort()Values, high to lowYes
ksort()Keys, low to highYes
krsort()Keys, high to lowYes
usort()Values using your own functionNo
uasort() / uksort()Values / keys using your own functionYes

For text with numbers like “img2” and “img10”, natsort() gives a natural order. Here is a custom sort with usort().

<?php
$people = [["Anil", 30], ["Robin", 25], ["Zoya", 22]];

usort($people, fn($a, $b) => $a[1] <=> $b[1]);   // by age

echo $people[0][0];
?>

Output:

Tutorials Class - Output Window

Zoya

See more examples in PHP Array Functions and ksort().

What is include() function in PHP?

The include statement takes all the code of another file and adds it to the current file, at the place where you write it. It is used to reuse parts like a header, a menu or a footer.

<?php
include "header.php";

echo "<p>Page content</p>";

include "footer.php";
?>

If the file is missing, include gives a warning, but the script continues. Related statements are include_once, require and require_once. See include() vs require() and PHP File Inclusion.

What are the different types of error in PHP?

PHP has four main types of errors at run time, plus deprecated messages.

TypeMeaningStops the script?
Parse errorWrong syntax, like a missing semicolon or bracketYes, nothing runs
Fatal errorA serious problem, like calling a function that does not existYes
WarningA problem, but PHP can go on, like a missing include fileNo
NoticeA small problem, like using an undefined variable (in PHP 8 this is a warning)No
DeprecatedYou use a feature that will be removed in futureNo

In PHP 7 and above many fatal errors are thrown as Error objects, so you can catch them. Learn how to show, hide and handle errors in PHP Errors.

How to define a Constant in PHP?

Use the define() function or the const keyword. A constant is like a variable, but its value can not change after it is set. It is used for values that rarely change, like a tax rate or the site name.

<?php
define("TAX_RATE", 18);
const SITE_NAME = "Tutorials Class";

echo SITE_NAME . " tax: " . TAX_RATE . "%";
?>

Output:

Tutorials Class - Output Window

Tutorials Class tax: 18%

Do not write the dollar sign ($) before a constant name. By convention names are in capital letters. Read all the rules in PHP Constants, and see the constant() function.

How will you concatenate two strings in PHP?

To join (concatenate) two strings in PHP, use the dot operator (.). To add text at the end of an existing variable, use .=.

<?php
$first = "Hello";
$second = "World";

echo $first . " " . $second . "<br>";

$text = "Hello";
$text .= " PHP";
echo $text . "<br>";

echo "$first $second";
?>

Output:

Tutorials Class - Output Window

Hello World
Hello PHP
Hello World

The last line puts the variables inside double quotes, which also works. Remember that the plus sign (+) does not join strings in PHP like in JavaScript, it tries to add numbers. Read more in PHP String Handling.

PHP’s numerically indexed array begins with which position?

A numerically indexed array in PHP begins with position 0, not 1. The first element has the key 0, the second has 1, and so on.

<?php
$array = [15, 80, 67, 33];

echo $array[0] . "<br>";
echo $array[3];
?>

Output:

Tutorials Class - Output Window

15
33

This array has 4 elements, so the keys are 0, 1, 2 and 3. If you try $array[4], PHP shows a warning “Undefined array key 4”, because there is no element at that position. The last key is always count($array) - 1.

What is the difference between single quote and double quote string in PHP?

In PHP a string can be written in single quotes or double quotes. They work differently:

Single quotes (‘ ‘)Double quotes (” “)
Text is used exactly as writtenVariables inside are replaced with their values
Only \' and \\ are specialEscape codes like \n, \t and \" work
Good for plain textGood when you need variables inside the text
<?php
$name = "Robin";

echo 'Hello $name' . "<br>";
echo "Hello $name" . "<br>";
echo "Price: {$name}s";
?>

Output:

Tutorials Class - Output Window

Hello $name
Hello Robin
Price: Robins

The curly braces in the last line mark where the variable name ends.

Note: You may read that single quotes are faster. The difference is so tiny that you will never notice it, so choose by need, not by speed. For long text on many lines use heredoc (like double quotes) or nowdoc (like single quotes). See PHP String Handling.

Which PHP function inserts an element to the end of an array?

Use array_push() to add one or more elements to the end of an array. A shorter way for one element is $array[] = value.

<?php
$fruits = ["Apple", "Banana"];

array_push($fruits, "Mango", "Orange");
$fruits[] = "Grapes";

print_r($fruits);
?>

Output:

Tutorials Class - Output Window

Array
(
[0] => Apple
[1] => Banana
[2] => Mango
[3] => Orange
[4] => Grapes
)

To add an element at the start use array_unshift(). To remove the last or the first element use array_pop() and array_shift(). See PHP Array Functions.

Why we use PHP String functions trim(), ltrim() and rtrim()?

These functions remove white spaces (or other characters that you give) from the ends of a string. They are useful to clean the input of a form.

FunctionRemoves from
trim()Both sides
ltrim()Left side (start)
rtrim()Right side (end)
<?php
echo "[" . trim("  Welcome  ") . "]<br>";
echo trim("--Hello--", "-") . "<br>";
echo ltrim("007", "0") . "<br>";
echo rtrim("Hello!!!", "!");
?>

Output:

Tutorials Class - Output Window

[Welcome]
Hello
7
Hello

The second parameter is a list of characters to remove. If you skip it, PHP removes spaces, tabs, new lines and a few more invisible characters. These functions do not remove spaces from the middle of a string, see how to remove all white spaces.

Which PHP function can be used check if variable is an array?

Use the is_array() function. It returns true if the variable is an array and false if it is not.

<?php
var_dump(is_array([1, 2, 3]));
var_dump(is_array("Hello"));
var_dump(is_array(null));
?>

Output:

Tutorials Class - Output Window

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

There are similar functions for other types, like is_string(), is_int() and is_bool(). See how to check the data type of a variable.