Top PHP Interview Questions and Answers (2021)

PHP Interview Questions

PHP is a widely-used general-purpose scripting language that can be embedded into HTML. It is quite popular for web development as well because it can generate dynamic content.  

 

It is an open-source scripting language.PHP code is executed on the server and then the subsequent plain HTML is sent to the client/browser, without exposing the actual code. It is so popular and powerful that applications like WordPress, Drupal, and Facebook are written in PHP. 

 

Below are the most frequently asked popular interview questions on PHP. 

Basic PHP interview questions: 

1. What do you understand about PEAR in PHP? 

 PEAR means PHP Extension and Application Repository. It is a community-driven framework/library which provides: 

  • A structured library of PHP code. 
  • Standard reusable components. 
  • Standard coding style. 
  • Framework for distribution of code and package maintenance. 

 

2. State the differences between variables and constants in PHP. 

Variables  Constants 
Variables can change values during program execution.  Constants remain unchanged(constant) 

during program execution. 

Use of a dollar sign ($) is required before their name.  

 

E.g., $book = “PHP For Beginners”; 

Use of a dollar sign($) is not required before their name. 

 

E.g., define(“book”, ”PHP For Beginners”); 

Can be defined by using an assignment(=) 

operator. 

Cannot be defined by using an assignment(=) operator. Requires use of define() function to define it. 

 

3. Explain different types of PHP variables. 

  • Integer: It is a non-decimal signed number(positive or negative). 
  • Float (Double): It is a decimal number or exponential number. 
  • Boolean: It can be either True or False. 
  • String: It is a string of characters. 
  • Array: It is a collection of similar types of data stored under a single name 
  • Object: It has methods and data as a single unit called class. 
  • NULL: It is a special data type which can store only one value- NULL. 
  • Resource: It is a special data type which stores reference to external resources. 

 

4. How can we compare objects in PHP? 

There are two ways to compare objects in PHP: 

  • Comparison operator(==) 

Checks if two objects are instances of a class with the same property values, i.e. same attributes and values. 

 

  • Identity operator(===) 

Checks if two objects are referencing the same instance of a class. 

 

The below table summarises the return value of both operators: 

Deciding Factor  Comparison operator(==) returns  Identity operator(===) returns 
Two objects referencing the same object instance.  True  True 
Objects with the same properties  True  False 
Objects with different properties  False  False 

 

5. Mention differences between print and echo. 

print   echo 
Outputs only one string  Outputs one or more strings 
Syntax: 

print ($argument1) 

Syntax: 

echo ($argument1, $argument2…) 

Slower than echo  Faster than print 
Returns 1  Returns nothing 
Parentheses are not required to pass more than one value  Parentheses are used for passing more than one value 

Read more with examples here. 

 

Intermediate interview questions: 

1. Explain the different types of arrays in PHP. 

PHP has three types of arrays: 

  • Indexed/ Numeric: The indexes are numeric and arrays are linear. 
Example: 

$organs[0]="heart";   

$organs[1]="lungs";   

$organs[2]="liver";   

$organs[3]="kidneys";

 

  • Associative: The index is a string and arrays are not linear. Each value stores named keys(user-defined strings). Which is in the form of key-value pairs. 
Example: 

$temperature["London"]="68";   

$temperature["Frankfurt"]="73";   

$temperature["Rome"]="85";

 

  • Multidimensional: Each array element stores a single or multiple arrays. It is an array of arrays. 
Example: 

$salary = array( 

            "Rob" => array ( 

            "Jan" => 45000, 

            "Feb" => 38000,  

            "Mar" => 41000 

            ), 

     

            "Sarah" => array ( 

            "Jan" => 48000, 

            "Feb" => 49000, 

            "Mar" => 47000 

            ) 

      );

 

2. Explain the different error types in PHP 

  • Fatal Error 

It is the most serious type of error, which causes program termination. Compiler compiles the code but cannot catch such fatal errors. 

Example:  Using an undeclared function in program 

 

  • Warning 

They do not interrupt the program run, however, they are also generated when some file is missing. They are less serious than a fatal error. 

Example: Calling a missing file 

 

  • Notice 

It is less serious than warning and is non-critical. It allows execution of the program. 

Example: Script is accessing an undefined variable 

 

  • Parse or Syntax Error 

Happens due to incorrect syntax in the code, it is a very common error. Compiler catches these types of errors during compilation. 

Example: missed semicolon, parentheses etc. 

 

3. What is a random function in PHP? 

The rand() function in PHP is used to generate random integers. The return value of the function is an integer. 

Syntax: 

  • rand() Without any limit, it generates integers between zero and getrandmax() function. 
  • rand(min, max): Generates random numbers within the specified limit. 

Example: 

If you want to generate random numbers between 1 to 100,  then use the rand function as below. It will generate random numbers inclusive of 1 and 100. 

rand(1,100) 

NOTE: The range provided by min and max should be within getrandmax(),  

i.e.,( max-min) <= getrandmax(). Otherwise poor quality random numbers will be returned. 

 

4. What are include() and require() functions in PHP? 

These functions help us to include PHP files in the code before execution. The include() and require() functions provide file inclusion property, which helps to reduce the redundant coding effort and size. The PHP code files which are already existing can be included(copied) in the current code file by these two functions. 

Syntax: 

<?php include 'filename.php';?> 
<?php require 'filename.php';?>

 

Difference: 

include()  require() 
Use it when the file is not required by the code. Because the script will continue execution if the file is not found.  Use it when the file is required by the code. Because the execution will be terminated if the file is not found. 
If the file is not found, it will produce a warning E_WARNING and the script execution will continue.  If the file is not found, it will produce a fatal error E_COMPILE_ERROR, and stop the script. 

 

Note: The best scenarios to use require() function are for files having library functions, configuration variables such as database configuration etc. Basically, the files which are mandatory or essential for the successful code run. 

 

Examples here. 

 

5. How can we create cookies in PHP? 

We can use the setcookie() function to create cookies in PHP. 

Syntax: 

setcookie(name, value, expire, path, domain, secure, httponly); 

Returns TRUE or FALSE based on success or failure. 

Example code: 

<?php 

$cookie_name = "user"; 

$cookie_value = "Jenny Klaus"; 

setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day 

?>

 

 6. What is ‘escaping to PHP’? 

Escaping is used in PHP to reduce the ambiguity of program interpreters. 

 

For example, there is a string which is mentioned in the program, we will write it within double quotes as – “I am a String”. Now, imagine we want to put more double quotes into it as- “I am a ”String””. This will cause ambiguity to the interpreter since it will not know where the string is ending. 

 

For such cases, we use escape sequences using a backslash (\). We will place a backslash before the double quote, where we want to stand it for itself. In this way, the interpreter will process the double quotes as is and not as the end of the string.  

Example: “I am a \”String\”” 

 

 7. How to redirect a page in PHP? 

PHP redirect is a server-side solution to redirect the user to a different page using the header() function.  

  •  It is a secure and fast process of redirection from one page to another. 
  • The header function should be written before HTML and DOCTYPE tags. 
  • Syntax: header( $header, $replace, $http_response_code ) 
  • The response codes are set to provide more information about redirection. 
    • 302: If not specified, the default value of the response code is 302, which is temporary redirection. 
    • 301: Permanent redirection 
Example: 

<?php 

header("Location: http://www.redirect.com/another-page.php"); 

exit(); 

?>

 

Without a header() function the page can be redirected using JavaScript. However, this is going to be slower as compared to the header() function. 

 

8. Explain $_SESSION in PHP? 

PHP creates a session to store and pass the information between pages. This session data is stored on the server, unlike cookies which get stored on the user’s system. 

 

Available session variables are stored in a superglobal associative array called $_SESSION in PHP.  

 

They are stored as a key-value pair in the array. These values are available for access during the lifetime of a session.  

 

We can set and get the session variables using this array. 

  • Example set variable: 

$_SESSION[“login”] = “Claura”;   

 

  • Example get variable: 

echo $_SESSION[“login”];   

 

Advanced interview questions: 

1. How can we terminate the script execution in PHP? 

The exit() function is an in-built PHP function which is used to terminate script execution. It outputs a message first and then terminates the script. 

  • The shutdown functions and object destroyers are independent of the exit() function and they will be executed even if the script is terminated. 
  • Whatever string is passed to the exit() function, it will be displayed before termination. 
  • It can be called without parentheses because it is a language construct. 

Syntax: 

exit(string $status = ?): void 

If status is a string, it will be displayed just before termination. 

 

exit(int $status): void 

If status is an integer, it will be used as an exit status and will not be printed. 

 

 2. How can we connect to a URL in PHP? 

To connect to a URL, we can use cURL (Client for URLs), a default library in PHP. The client issues a GET request and receives the information which has been asked, such as headers, HTML, etc. There are cURL functions available to support these actions they are: 

  • curl_init(): To initialise the cURL session 
  • curl_setopt(): To set all options for transfer 
  • curl_exec():To execute the session 
  • curl_close(): To close the session 

 

Below example shows use of cURL for downloading contents of a remote website into a local file. 

<?php 

$handle = curl_init(); 

$url = "https://www.ladygaga.com"; 

  

// Set the url 

curl_setopt($handle, CURLOPT_URL, $url); 

// Set the result output to be a string. 

curl_setopt($handle, CURLOPT_RETURNTRANSFER, true); 

  

$output = curl_exec($handle); 

  

curl_close($handle); 

  

echo $output; 

?>

 

 3. Why is callback used in PHP? 

A callback function is a function which can be passed as an argument into another function. They are denoted by a callable type and their name is passed in the calling function as an argument. 

Example: Pass a callback to PHP’s array_map function. 

<?php 

function my_callback($item) { 

  return strlen($item); 

} 

$strings = ["apple", "orange", "banana", "coconut"]; 

$lengths = array_map("my_callback", $strings); 

print_r($lengths); 

?>  

 

 4. Will it be possible to extend the execution time of PHP? 

The maximum execution time is defined by max_execution_time directive. 

 

After PHP reaches the maximum execution time, a fatal error will be generated and PHP will timeout and exit. 

 

Fatal error: Maximum execution time of 30 seconds exceeded in example.php 

 

If the execution time is not set then the default value is 30 seconds. There are below ways to increase the execution time: 

 

5. Explain major differences between for loop and foreach loop.  

For loop  Foreach loop 
It is executed over variables  Executed on Arrays- associative and numerical 
Executes till the given condition is true  Executes until there are elements in the array 
Syntax: 

 

for ( initialisation; condition; increment) 

{ 

Code to be executed; 

} 

Syntax: 

 

foreach ($array as $value) 

 { 

  Code to be executed; 

} 

 

Related Articles

Responses

HACKERBUCK AWARDED