Top 100+ PHP Interview Questions and Answers

1.
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.
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?
  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.
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 given code prints 'world' as output.

<?php 
$var = "hello"; $$var = "world"; echo $hello;
?>
8.
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 -
$_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. 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




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 can be useful if you need to define some constant data within a class. 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 And
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?
  The final keyword is used only for methods and classes. 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, the $_FILES superglobal array, we can get information about the uploaded file.
19.
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.




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?
  To call the constructor of the parent class from the constructor of the child class, you use the following syntax -
parent::constructor($name);
23.
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.
24.
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.
25.
How to get the number of result rows?
  We can find the number of result rows using the 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?
  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.

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 provides method_exists() function 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 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.

Example

<?php
    $arr = mkdir('c', '0777', true);
?>
35.
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.

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?
  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.
39.
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.
40.
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.
41.
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.

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?
  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.

Syntax

getdate(timestamp);

Here, timestamp is optional parameter. 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?
  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.




48.
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.

Syntax

mt_rand(min, max);

The 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?
  The 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?
  The getenv() function is used to get the value of an environment variable. All the environment variables are defined in the php.ini file.

Syntax

getenv(variable);

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

Example

<?php
    $admin = getenv("SERVER_ADMIN");
    echo $admin;
?>
53.
How to calculate exponents in PHP?
  By using the exp() function, we can calculate the exponent in PHP.

Syntax

exp(value);

Here, 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 in PHP array?
  This function is used to return the last element of an array.

Syntax

end(arrayname);

Here, 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 in PHP?
  The 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?
  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.

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?
  The PHP rand() 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 in PHP?
  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?
  The count() function 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 = "This email address is being protected from spambots. You need JavaScript enabled to view it., This email address is being protected from spambots. You need JavaScript enabled to view it., This email address is being protected from spambots. You need JavaScript enabled to view it.";
$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()?
  The 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?
  The 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?
  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.
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?
  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.

85.
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.
86.
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.
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?
  The .htaccess is a configuration file for use on web servers running the Apache Web Server software.
96.
Write code to redirect a URL to secure https using .htaccess.
 
RewriteEngine on
RewriteCond %{HTTPS} off
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]
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?
  The 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 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.
100.
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.
101.
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.
__construct()
__destruct()
__get()
__unset()
__autoload()
__set()
__isset()
102.
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.
103.
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.
104.
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.