Top 100+ PHP Interview Questions and Answers

What is PHP?
PHP stands for 'Hypertext Preprocessor'. PHP is a procedural and object-oriented language. It is server-side scripting or programming language which is very easy to learn and understand.
Who created PHP programming language and when?
Rasmus Lerdorf was created PHP programming language in 1995.
What is the first version of PHP?
PHP/FI (Personal Home Page/ Form Interpreter ) is the first version of PHP.
When PHP3 was released?
Andi Gutmans and Zeev Suraski worked with Rasmus Lerdorf and released PHP3 in 1998.
What were the major changes in PHP4 release?
PHP4 was released with Zend Engine 1.0, that improved the complex execution process and increased the performance.
What are the major features of PHP5?
PHP5 was released with Zend Engine II. PHP5 rich in Object Oriented features and some other important features like PDO extesions to provide secure connection from databases.
What is indirect variable reference?
In PHP, we can access variable by using indirect reference. With this, value of one variable can be used as a variable holding some other value.
The given code prints 'world' as output.

$var = "hello"; $$var = "world"; echo $hello;
What is Super global variables in PHP give some example?
Superglobal variables are predefined variables in PHP. These variables can be accessible from any scope of the script.

Types of superglobal variables are -
Define Array in PHP?
An array is a collection of key/value pairs. An array is a variable that can store one or more than one values. To create an array, PHP provides an array() construct. Each element in an array is separated by a comma.
There are three types of array used in PHP -
1) Indexed Array
2) Associative Array
3) Multidimensional Array

Define constant in PHP ?
Constant is an identifier of simple value. It is defined at once and globally access in script. We can define constant using define() function. PHP also contains some predefined reserve constants like PHP_VERSION, E_ERROR and magic constants like _FILE_, _DIR_, _LINE_ etc.
What is the role of $this variable?
$this is used to reference the current object. By using $this, we can call methods of the current class.
Differentiate between public, protected and private access specifiers?
The public access specifier can be accessed from any scope.
The private access specifier can be accessed within the class only.
The protected access specifier can be accessed within the class and within the inheritance classes and child classes.
Define static methods and properties?
Static methods and properties are not bound to any specific object means they cannot be accessed through the object and ->, we can call them by using the scope resolution operator (::).
Define class constants?
Class constants are declared within the class and differ from the normal variable and remain unchangeable. Class constants can be useful if you need to define some constant data within a class. Class constants are always case sensitive.

Example -
const EMP = 'employee'; 
What is the difference between parent:: And self::?
self:: refers to the current class and usually used to access static member, method and constant And
parent:: refers to the parent class and used to call parent class constructor and method.
What is an Interface?
PHP does not support multiple inheritance instead it choose interface. A class that implements an interface has an instance (is-a) relationship.
What is the Final Method in PHP?
The final keyword is used only for methods and classes. When we declare a method as Final then the child class cannot override them.
How to get information about the uploaded file in a form?
By using, the $_FILES superglobal array, we can get information about the uploaded file.
Define some predefined keys of FILE array and its uses?
PHP has a global array $_FILES, to handle the file upload. This array returns the following data of the uploaded files.
$_FILES['name']- To get the name of the uploaded file.
$_FILES['type']- To get the MIME type of the uploaded file.
$_FILES['tmp_name']- To get the temporary file name stored on the server's file system. Later this will be clean up after the request has finished.
$_FILES['size']- To get size in bytes of the uploaded file.

What is the difference between include and require?
Both include and require function includes the file in the same way, the main difference is that if the file is not found, then the require function will throw a fatal error E_COMPLIE_ERROR which will stop the execution of the script but the include function will return a warning and continue the execution of the script.
What is the difference between Session and Cookie?
The main difference between Session and Cookie is that Session data is stored on the server. That data are kept on the server until we close the browser, whereas Cookies store data in the visitor's browser and remains in the browser until we delete the data.
How to call parent class constructor within the child class?
To call the constructor of the parent class from the constructor of the child class, you use the following syntax -

What is the role of die() function?
The die() function is equivalent to exit. It exits the current script and returns the argument pass in it.
What is the difference between strpos() and strrpos() function?
The strpos() function finds the position of the occurrence of a substring inside another string, whereas the strrpos() function finds the position of the last occurrence of a substring inside another string.
How to get the number of result rows?
We can find the number of result rows using the mysql_num_rows() function.

$result = mysql_query($query, $con);
$num_rows = mysql_num_rows($result);
echo $num_rows;?>
How does array_diff work in PHP?
The array_diff function() is used to get array differences. This function returns those values from the first array that are not present in other arrays.
Output of the below code -
Array ([1]=> blue, [2]=> yellow))
$array1=array("green", "red", "blue", "red");
$array2=array("green", "yellow", "red");

What are the different types of error in PHP?
There are basically four types of error in PHP.

a) Parse Error - It occurs during compilation. If there is any syntax error in the script, then it stops the execution of that script.

b) Fatal Error - These are critical errors that terminate the execution of the script. It occurs if we are calling non-existent function or class.

c) Notice - These are non-critical errors, that occur when accessing a variable that has not been defined. It does not stop the execution of the script.

d) Warning - It occurs during run time and does not result in script termination. Like, include a file which does not exist or passing the incorrect number of parameters in a function.
What is the difference between echo and print?
Echo accepts a multiple string / expression while print does not pass multiple arguments, it returns a single string. Echo executes faster than print. Echo has no return value while print has a return value of one, so it can be used in expressions.
How to change the maximum execution time in PHP?
We can modify the max_execution_time limit in PHP global configuration file, this will affect all the execution of the scripts that run on the system. If there is required to increase maximum execution time of a particular script, then we can call the set_time_limit function in the desired script and pass the maximum execution time.
How many ways are there to retrieve the data in the result set of MySQL?
There are four ways to retrieve the data in the result set.

a) mysqli_fetch_row
b) mysqli_fetch_object
c) mysqli_fetch_array
d) mysqli_fetch_assoc
What is the use of hash() function?
The hash() function is used to convert data in hash form. This is used for security purpose to convert messages, username, password in hash format.


hash(algorithmname, string, rowoutput);
First parameter is the algorithm name like sha1, md5, sha2, sha512. Second parameter is the string that will be hashed. rowoutput is optional, if it is set to TRUE, then it returns raw binary data and if set to FALSE then returns lowercase.
What is the use of isset() function?
This function is used to check whether a variable is set with a value or null.


The parameter 'variablename' is the required field. It returns true if the variable is set with a value and false otherwise.


    $var1 = 'Hello World';
    if(isset($var1)) {
        echo 'variable is set a value';
    if(isset($var2)) {
        echo 'variable is set a value';
        echo 'variable is null';

How to check existence of a method in a given object?
PHP provides method_exists() function to check the existence of a method in a given object.


method_exists(objectname, methodname);

Both parameters objectname and methodname are the required fields.


    class Demo {
        function funcdemo(){
            echo 'Hello World';
    $demo = new Demo();
    if(method_exists($demo, funcdemo)) {
        echo 'function exist in the given object';

How to create a directory in a specified location?
By using PHP mkdir() function, you can create directory in the specified location and path.


mkdir(pathname, mode, recursion);

The parameter pathname is the location where directory is created. , the mode is the access permission, by default it is 0777. The recursion is used to create a nested path. It is a boolean value, either true or false. The mkdir() function returns boolean value. If a directory is successfully created, then it returns true, otherwise it returns false.


    $arr = mkdir('c', '0777', true);

What is NULL datatype?
The NULL data type has only one possible value, i.e. NULL. If a variable has no any value assigned, then it has a null value. It returns false when pass on ISSET operator.


    $var = NULL;
        echo 'Null value' ;

What is resources in PHP?
Resources are special variables holding references to the external resources. Example - curl, imap
Difference between Local Scope and Global Scope of variable.
PHP variable declares outside of a function has global scope. The value of the variable has remained same until it is not reassigned other value.
PHP variable declares inside a function has local scope.
How to check existence of array index in an array?
PHP provides array_key_exists() function to check the existence of the given array index in the array. It returns true if the given key is set in the array.
How to get the information of the current user in PHP?
The get_current_user() function is used to get the information of the current PHP script.
Define implode and explode?
The implode() function is used to convert array elements into string and the explode() function is used to split a string into multiple strings based on the specified delimiter.
Define md5() function in PHP?
PHP string md5() is predefined function. It is used to calculate hash value of a string. It returns the hash as a 32 character hexadecimal number.



String is the required parameter. It returns hash value of the given string.


    $str = 'Hello world';
    echo md5($str);

Difference between Break and Continue?
The break statement is placed inside the loop to terminate the iteration and start to execute the code immediately after the loop and the continue statement is also used inside a loop. When continue statement is executed, it stops the current iteration of the loop and continue with the next iteration of the loop.
What is a function?
Function is a name to some lines of code, so that if that lines of code are used in multiple places, then that can be replaced by just one line of code containing the defined function name.
What is method overriding?
If the method in the child class has same name, same parameters as in its parent class, it is called method overriding.
How to get current date and time information?
The getdate() function is used to get current data and time information. It returns an associative array containing date information of the localtime or the specified timestamp.



Here, timestamp is optional parameter. If it is not specified then, it returns date information of the given timestamp.


    $today_dateinfo = getdate($today_dateinfo);
    echo '<pre>'; print_r();

What is Encapsulation?
Encapsulation is the process of wrapping up data and method into a single unit( i.e. object). It secures the data from direct interaction.
How to initiate a session in php?
The session_start() method is used to initiate a session. It will create a new session and generate a unique session ID for the user.

What is the use of mt_rand() function?
The mt_rand() function is used to return random number. It generates a random integer between the specified minimum and maximum values. This is faster than the rand function.


mt_rand(min, max);

The min and max are optional parameters.


    echo mt_rand().'<br/>';
    echo mt_rand().'<br/>';
    echo mt_rand('1', '4').'<br/>';

What is Constructors?
The constructors are declared inside a class like a function. It starts with two underscores and method name construct. It calls automatically while creating an object. We can pass parameters to the constructor while creating an object.
What is Destructors?
The destructors are declared inside a class. It starts with two underscores and method name destruct. It automatically destroys an object when no longer needed.
How to get a value at the next array pointer?
The next() function is used to get the value at the next array pointer from the given location.



What is the use of getenv() function?
The getenv() function is used to get the value of an environment variable. All the environment variables are defined in the php.ini file.



Here, the variable is the required parameter. If the variable name does not exist in the php.ini file, then it returns false.


    $admin = getenv("SERVER_ADMIN");
    echo $admin;

How to calculate exponents in PHP?
By using the exp() function, we can calculate the exponent in PHP.



Here, value is the required parameter.


    $var = 10;
    $var1 = 2;
    $var2 = 1.5;
    $var3 = 10.5';
    echo exp($var).'<br/>';
    echo exp($var1).'<br/>';
    echo exp($var2).'<br/>';
    echo exp($var3).'<br/>';

What is the use of end() function in PHP array?
This function is used to return the last element of an array.



Here, arrayname is the required parameter. It returns last element of an array.


    $arr = array('10', '11', '55', '90');
    $arr1 = array('car', 'bike', 'cycle');
    echo end($arr).'<br/>';
    echo end($arr1).'<br/>';

What is the role of new operator in PHP?
The new operator is used to create an instance of a class.
What is the use of ksort() function?
This function is used to sort array elements by its key. This is generally used in the associative array.


ksort(array_name, sort_flags);

array_name is the required parameter. sort_flags is optional and used to set sorting behavior.


    $arr = array('0'->'car', '10'->'train', 
                 '12'->'bus', '1'->'cycle');
    $arr_sort = ksort($arr);
What is each() function?
This is used to return the current key value pair of an array and move the internal pointer to the next element.



$array is the required parameter.


    $arr = array('1'=>'car' , '2'=> 'bus',     
                 '3'=>'train', '4'=> 'cycle');
    echo each($arr);

What is the use of PHP int_set() function?
The ini_set() function is used to set the configuration value. It allows us to change system attributes that affect the way your script is executed.


int_set("key", "value");


    int_set("memory limit", "100M");
    int_set("display_error", '1');	
    int_set("upload_max_filesize", '10M');	

Define PHP rand() function?
The PHP rand() function is used to generate the random number. You can also set the specific range to generate the number.


rand("min", "max");

Min and Max are optional values, if these values are set, then the random number will be between these values.

What are the different types of error reporting levels?
These are the different types of error levels.
To turn off all errors = ERROR_REPORTING(0);
To display only warning = ERROR_REPORTING(E_WARNING);
To display only parse errors = ERROR_REPORTING(E_PARSE);
To display all types of errors = ERROR_REPORTING(E_ALL);
To display only notice error type = ERROR_REPORTING(E_NOTICE);
To hide notice and display all errors = ERROR_REPORTING(E_ALL & ~E_NOTICE);

How to display all errors except notice in PHP?
To hide notice and display all errors - ERROR_REPORTING(E_ALL & ~E_NOTICE);
What is exit() function?
This function returns the message, error code and terminates the script.



It accepts one parameter message or error number and the given message displays on the screen before termination.


   echo 'Welcome to etutorials';
   exit('Terminate the code execution'); 
   echo 'This will not execute as this is after the exit function';

What is the use of urlencode and urldecode in PHP?
Urlencode returns the URL encoded version of a given string and pass in the url and the urldecode returns the original string from the encoded string.
What is PDO?
PDO extends for PHP Data Object. It is lightweight, more portable interface for accessing database in PHP. To perform database operation using PDO, we need database PDO Driver. With the help of PDO, we can use prepared statement features in MySql
How POST argument is more secure than GET?
POST is more secure than GET because user-entered information is never visible in the URL query string, in the server logs and on screen.
How to capitalize the first letter of each word in a string?
The ucwords() function is used to capitalize the first letter of each word in a string.
How will you delete an element from an array?
By using unset(), we can delete an element from an array. For this, you have to pass the array name with index number in unset().
What is the use of count() function?
The count() function takes an array as argument and returns the number of nonempty elements in an array.
What is the basic command to initiate a MYSQL connection?


$conn = mysqli_connect('hostname','username',                   

What is the purpose of foreach() loop?
foreach loop is exclusive for arrays. It iterates an array with key or without key entirely in same order as that array contains.
Are the operator && and 'and' interchangeable?
Both operators && and AND are theoretically same and can be interchangeable. But if precedence is important, then && is preferable because && has a high precedence then AND.
How will you send mail to multiple recipients in PHP?
$emails = ",,";
$mailsend = mail($emails, $subject, $body);
echo $mailsend;

What is the difference between foreach() and each() function?
Both the each and the foreach function return elements from an array. The difference is that the each function returns just a single element, so it is usually wrapped in a loop. The foreach loop execute repeatedly until the array is exhausted.
What is the use of compact() function?
This function is used to create an array from variables and their values.


      $emp_name = "John";
      $age = "30";
      $city = "Goa";
      $employe = compact('emp_name', 'age', 'city');

Which PHP function enables the running of system commands?
The PHP function exec enabled the running of system commands.
What is a getDate()?
The getDate() function returns an array of values containing different components of the current date and time.
How you will check a particular valid date?
We can check a valid date by using checkdate() function.
What is display_errors?
display_errors is a configuration variable defined in php.ini. If display_errors is turned on, errors are displayed to the scripts output location.
Which function you will use to compare two strings with case insensitively?
By using strcasecmp() function, we can match two strings case insensitively.


   $var1 = 'Hello World';
   if (strcasecmp($var1, "hello world") === 0) {
      echo 'Both are equal.';

What is the use of strtotime() function?
The strtotime() function is used for converting a human readable data value to a UNIX timestamp.
How can we get Client IP Address using PHP?
By using $_SERVER['HTTP_CLIENT_IP'], we can get client IP address.
What are SQL Injection?
The SQL Injection is one of the oldest code-injection techniques which the attackers generally used to exploit the web applications. By using this, the attacker can violate transactions, they can become an administrator of database, or they can also effect our bank balance.
How do you prevent SQL injections?
These are the methods that protect from SQL Vulnerabilities -

1. mysql_real_escape_string()
2. By using MySQLi
3. By using PDO

Click Here to know more

How to set a Cookie in PHP?
Cookies are pieces of content that are sent to a user's web browser. The setcookie() function is used to set a cookie in PHP.
Syntax to set cookie -
setcookie(name, value, expire, path, domain, secure, httponly);

Here, only the 'name' parameter is required. All other parameters are optional. Examples of setcookie() -

setcookie("name", "Smith", time()+3600, "/","", 0);
   setcookie("department", "IT", time()+3600, "/", "",  0);

The above example creates two cookies named "name" and "department" with the values "Smith" and "IT". Both cookies will be expired after one hour.

What is the use of php.ini file?
The PHP.ini is very useful and it is a configuration file that is used to customize behavior of PHP at runtime.
What is MVC?
The Model-view-controller (MVC) is an architectural pattern commonly used for developing user interfaces that divides an application into three interconnected parts- the model, the view, and the controller.
What is the difference between == and === in PHP?
The difference between the two is that '==' should be used to check if the values of the two operands are equal or not. On the other hand, '===' checks the values as well as the type of operands.
How to retrieve a cookie value?
By using PHP Cookie global variable, we can retrieve a cookie value-
$cookie_name = 'username';
echo $_COOKIE[$cookie_name];
What is the difference between mysqli_fetch_object() and mysqli_fetch_array()?
The mysqli_fetch_object() function collects the first single matching record where mysqli_fetch_array() collects all matching records from the table in an array.
What are the PHP PDO methods to retrieve the data in the result set of MySQL?
These are the PHP PDO methods to retrieve the data in the result set of MySQL-

How to stop PHP code execution?
PHP exit() method is used to stop the PHP code execution.
How will you open a file in readonly mode?
We can open a file in read only mode by using second parameter "r" in fopen() function.
Example - fopen("filename", "r");
Is it possible to change the value of a constant during script's execution?
No, we cannot change the value of a constant during script's execution.
What is the default session time in PHP?
By default the session time in PHP is 24 minutes, but it can vary based on your server configuration.
What is a .htacces file in PHP?
The .htaccess is a configuration file for use on web servers running the Apache Web Server software.
Write code to redirect a URL to secure https using .htaccess.
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
What is the use of PHP htmlentities() function?
The htmlspecialchars() function converts some predefined characters to HTML entities.

What is the use of file_get_contents() function?
The file_get_contents() function is used for reading a file and storing it in a string variable.
How to get image size, width and height in PHP?
The getimagesize() function is used to get the image size, the imagesx() function is used to get the image width and the imagesy() function is used to get the image height.
Which function is used to get number of parameters passed into a function?
The fun_num_args() function is used to get number of parameters passed into a function.
What are magic methods?
Magic methods in PHP are special methods that start with two underscores and have unique names to perform certain tasks. Magical methods always lives in a PHP class.
What is the purpose of _LINE_ constant in PHP?
The _LINE_ constant in PHP is used to get the current line number of the file.
What is the use of cURL()?
The cURL stands for client URL, it is a tool for getting and sending data using various protocols, like - GET, POST, FTP, COOKIES, SMTP and many more. The curl_setopt() function is used to set an option for a curl transfer. It returns a boolean value, i.e., either TRUE or FALSE.
What is GD library in PHP?
The GD library is utilized for dynamic picture creation. In PHP, we can easily use the GD library to make GIF, PNG or JPG pictures quickly from our code.
If you are unsure that you have GD library, you can run phpinfo() to watch that GD Support is enabled. On the off chance that you don't have it, you can download it for free.

Read more articles

General Knowledge

Learn Popular Language