Top 100+ PHP Interview Questions and Answers

1.
What is PHP?
PHP stands for 'Hypertext Preprocessor'. It is a server side scripting and programming language that is widely used for web development.
2.
Who created PHP programming language and when?
Rasmus Lerdorf was created PHP programming language in 1995.
3.
What is the first version of PHP?
PHP/FI (Personal Home Page/ Form Interpreter ) is the first version of PHP. 
4.
When PHP3 was released?
Andi Gutmans and Zeev Suraski worked with Rasmus Lerdorf and released PHP3 in 1998.
5.
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.
6.
What are the major features of PHP5?
PHP 5 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.
7.
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 code below print 'world' as output.

<?php 
$var = "hello"; $$var = "world"; echo $hello;
?>
8.
Define Super Global variables in PHP with example.
Superglobal variables are predefined variables in PHP. These variables can be accessible from any scope of the script.

Types of Superglobal variables are -
$_GET, $_POST, $_EVE, $_FILES, $_SERVER, $_SESSION, $_COOKIE, $_REQUEST
9.
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.
There are three types of array used in PHP -
1) Indexed Array
2) Associative Array
3) Multidimensional Array
10.
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.
11.
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.
12.
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.
13.
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(::).
14.
Define class constants?
Class constants are declared within the class and differ from the normal variable and remain unchangeable. Class constants are always case sensitive.

Example -
const EMP = 'employee';
15.
What is the difference between parent:: And self::?
self:: refers to the current class and usually used to access static member, method and constant.
parent:: refers to the parent class and used to call parent class constructor and method.
16.
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.
17.
What is the Final Method in PHP?
When we declare a method as Final then the child class cannot override them.
18.
How to get information about the uploaded file in a form?
By using $_FILES superglobal array, we can get information about the uploaded file.
19.
Define some predefined keys of FILE array and its uses?
$_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.
20.
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.
21.
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.
22.
How to call parent class constructor within the child class?
parent::constructor($name);
23.
What is the role of die() function?
die() is equivalent to exit. It exits the current script and returns the argument pass in it.
24.
What  is the difference between strpos() and strrpos() function?
strpos() function finds the position of the occurrence of a substring inside another string, whereas strrpos() function finds the position of the last occurrence of a substring inside another string.
25.
How to get the number of result rows?
We can find the number of result rows using mysql_num_rows function.

<?php 
$result = mysql_query($query, $con); $num_rows = mysql_num_rows($result); echo $num_rows;
?>
26.
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))
<?php 
$array1=array("green", "red", "blue", "red"); $array2=array("green", "yellow", "red"); $array3=array("green"); $result=array_diff($array1,$array2,$array3); print_r($result);
?>
27.
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.
28.
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.
29.
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.
30.
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 
31.
What is the use of hash() function?
This function is used to convert data in hash form. This is used for security purpose to convert messages, username, password in hash format.

Syntax

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.
32.
What is the use of isset() function?
This function is used to check whether a variable is set with a value or null.

Syntax

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

Example

<?php
    $var1 = 'Hello World';
    $var2;
    if(isset($var1)) {
        echo 'variable is set a value';
    }
    if(isset($var2)) {
        echo 'variable is set a value';
    }
    else{
        echo 'variable is null';
    }
?>

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

Syntax

method_exists(objectname, methodname);

Both parameters objectname and methodname are the required fields.

Example

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

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

Syntax

mkdir(pathname, mode, recursion);

The pathname is the location where directory is created. The mode is the access permission, by default it is 0777. 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.

Example

<?php
    $arr = mkdir('c', '0777', true);
?>

35.
What is NULL datatype?
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.

Example

<?php
    $var = NULL;
    if(!isset($var){
        echo 'Null value' ;
    }
?>

36.
What is resources in PHP?
Resources are special variables holding references to the external resources. Example - curl, imap
37.
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.
38.
How to check existence of array index in an array?
array_key_exists function is used to check the existence of the given array index in the array.
39.
How to get the information of the current user?
get_current_user() function is used to get the information of the current file.
40.
Define implode and explode?
implode function is used to convert array elements into string and explode function is used to split a string into multiple strings based on the specified delimiter.
41.
Define md5?
md5 function is used to generate hash value of a string.

Syntax

md5(string);

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

Example

<?php
    $str = 'Hello world';
    echo md5($str);
?>

42.
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.
43.
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.
44.
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.
45.
How to get current date and time information?
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.

Syntax

getdate(timestamp);

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

Example

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

46.
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.
47.
How to initiate a session in php?
session_start() method is used to initiate a session.
48.
What is the use of mt_rand() function?
This function is used to return random number. This is faster than rand function.

Syntax

mt_rand(min, max);

min and max are optional parameters.

Example

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

49.
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.
50.
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.
51.
How to get a value at the next array pointer?
next() function is used to get the value at the next array pointer from the given location.

Syntax

next(array);

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

Syntax

getenv(variable);

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

Example

<?php
    $admin = getenv("SERVER_ADMIN");
    echo $admin;
?>

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

Syntax

exp(value);

value is the required parameter.

Example

<?php
    $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/>';
?>

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

Syntax

end(arrayname);

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

Example

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

55.
What is the role of new operator?
new operator is used to create an instance of a class.
56.
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.

Syntax

ksort(array_name, sort_flags);

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

Example

<?php
    $arr = array('0'->'car', '10'->'train', 
                 '12'->'bus', '1'->'cycle');
    $arr_sort = ksort($arr);
?>
57.
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.

Syntax

each($array);

$array is the required parameter.

Example

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

58.
What is the use of PHP int_set() function?
This function is used to set the configuration value.

Syntax

int_set("key", "value");

Example

<?php
    int_set("memory limit", "100M");
    int_set("display_error", '1');	
    int_set("upload_max_filesize", '10M');	
?>

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

Syntax

rand("min", "max");

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


60.
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);
61.
How to display all errors except notice?
To hide notice and display all errors - ERROR_REPORTING(E_ALL & ~E_NOTICE);
62.
What is exit() function?
This function returns the message, error code and terminates the script.

Syntax

exit($message);

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

Example

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

63.
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.
64.
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
65.
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.
66.
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.
67.
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().
68.
What is the use of Count() function?
It takes an array as argument and returns the number of nonempty elements in an array.
69.
What is the basic command to initiate a MYSQL connection?

Example


<?php 
$conn = mysqli_connect('hostname','username',                   
                      'password','database');
?>

70.
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.
71.
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.
72.
How will you send mail to multiple recipients in PHP?
<?php 
$emails = "user1@domain.com, user2@domain.com, user3@domain.com";
$mailsend = mail($emails, $subject, $body);
echo $mailsend;
?>

73.
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.
74.
What is the use of compact() function?
This function is used to create an array from variables and their values.

Example

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

75.
Which PHP function enables the running of system commands?
The PHP function exec enabled the running of system commands.
76.
What is a getDate()?
getDate() function returns an array of values containing different components of the current date and time.
77.
How you will check a particular valid date?
We can check a valid date by using checkdate() function.
78.
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.
79.
Which function you will use to compare two strings with case insensitively?
By using strcasecmp() function, we can match two strings case insensitively.

Example

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

80.
What is the use of strtotime() function?
strtotime() function is used for converting a human readable data value to a UNIX timestamp.
81.
How can we get Client IP Address using PHP?
By using $_SERVER['HTTP_CLIENT_IP'], we can get client IP address.
82.
What are SQL Injection?
SQL injection is a code injection technique, used to attack data-driven applications, in which farious SQL statements are inserted into an entry field for execution.
83.
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
84.
How to set a Cookie in PHP?
The setcookie() function is used to set a cookie in PHP.
Syntax to set cookie -
setcookie(name, value, expire, path, domain, secure);

setcookie("username", "Smith", time()+30*24*60*60);
85.
What is the use of php.ini file?
PHP.ini is very useful and it is a configuration file that is used to customize behavior of PHP at runtime.
86.
What is MVC?
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.
87.
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.
88.
How to retrieve a cookie value?
By using PHP Cookie global variable, we can retrieve a cookie value-
<?php
$cookie_name = 'username';
echo $_COOKIE[$cookie_name];
?>
89.
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.
90.
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-

PDOStatement::fetch(PDO::FETCH_ASSOC)
PDOStatement::fetch(PDO::FETCH_OBJ)
PDOStatement::fetch()
PDOStatement::fetch(PDO::FETCH_NUM)
91.
How to stop PHP code execution?
PHP exit() method is used to stop the PHP code execution.
92.
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");
93.
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.
94.
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.
95.
What is a .htacces file in PHP?
.htaccess is a configuration file for use on web servers running the Apache Web Server software.
96.
What is a .htaccess file in PHP?
.htaccess is a configuration file for use on web server running the Apache Web Server software.
97.
What is the use of PHP htmlentities() function?
The htmlspecialchars() function converts some predefined characters to HTML entities.
98.
What is the use of file_get_contents() function?
file_get_contents() function is used for reading a file and storing it in a string variable.
99.
How to get image size, width and height in PHP?
The getimagesize() function is used for size, imagesx() is used for width and imagesy() is used for height.
100.
What is the use of file_get_contents() function?
file_get_contents() function is used for reading a file and storing it in a string variable.
101.
Which function is used to get number of parameters passed into a function?
fun_num_args() function is used to get number of parameters passed into a function.
102.
Write code to redirect a URL to secure https using .htaccess.
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]




Read more articles