All PHP Interview Questions & Answers

All PHP Interview Questions & Answers list

Here, you can find PHP Interview Questions & Answers related to Arrays, Operators, Loops, Variables, Conditional Statements, Strings, Form, MySQL, Cookies, and Sessions. These popular & frequently asked interview questions are listed under different categories.

Tutorials Class covers Interview Questions for Freshers as well as Experienced professionals. We not only list core PHP but also provide Advanced PHP interview questions for students.

How to terminate or break a loop in PHP?

By using break keyword in the loop, we can terminate or break a loop anywhere in PHP .

Example to break a PHP loop:

<?php
$months = array('jan', 'feb', 'mar', 'apr', 'stop', 'may');
foreach ($months as $month) {
    if ($month == 'stop') {
        break;    
    }
    echo "$month<br />";
}
?>

What is single line comment in PHP? Explain with syntax.

The single line comment tells the interpreter to ignore everything that occurs on that line to the right of the comment. To do a single line comment type // or # and all text to the right will be ignored by PHP interpreter.

Example of single line comment

<?php
#this is a single line comment
echo"this is an printing statement";
//this is also a single line comment
?>

How you can force maximum execution time error in PHP?

We can use sleep function to consume PHP execution time and it will throw PHP error.

<?php
  
  for($i=0; $i<10; $i++)
  {
    echo $i;
    sleep(300); //delay the exicution of the PHP script
  }
  ?>
Tutorials Class - Output Window

maximum execution time error in php

How can we set infinite execution time in PHP Script ?

By adding the set_time_limit(0) at the beginning of PHP script, we can set the infinite execution time for PHP Script.

Note: Note: This method will only work if you are allowed to change PHP configuration by Hosting Server.

How to increase maximum execution time in PHP and WordPress

We mostly see that the maximum execution time of a PHP Script is 30 seconds. If a script takes more than 30 seconds to execute, it will throw the following Fatal error.
Fatal error: Maximum execution time of 30 seconds exceeded in ….

We can increase maximum execution time in PHP and WordPress by using various methods. In the following examples, we have increased maximum execution time to 360 seconds (6 minutes).


Method 1: By adding the code in a PHP file:

We can set the maximum execution time by adding this code in a PHP File. You must add this code in that file which is included earlier in all other pages. Then this function will increase maximum execution time in all those files.
For example, put this code in the header (header.php), or configuration (config.php) if available.
set_time_limit(360);


Method 2: Inside the .htaccess file:

We can do the same thing inside the .htaccess file as well. Before editing this file, you make sure to have a backup of .htaccess.
php_value max_execution_time 360


Method 3: Inside the php.ini file:

We can also set the maximum execution time by adding this code in the php.ini file.
max_execution_time = 360


Method 4: Inside wp-config.php file in WordPress:

If you are using WordPress then you can place this code in wp-config.php file.
set_time_limit(360);


Note: Note: These methods will only work if you are allowed to change PHP configuration by your Hosting Server.

What is the difference between == and === Operators in PHP?

PHP equal operator (==) and idential operator (===) are Relational or Comparison Operators in PHP langauge.

The only difference is that === operator matches the values along with Data types. While == operator only match values but not Data types.


Example to see difference between both operators

<?php
 
$num_1 = 12;
$num_2 = 12.00;
 
if ($num_1 == $num_2) {
    echo "Value matched using ==";
} else {
    echo "Value is not matched using ==";
}
 
echo "<br> Now we will check using === operator <br>";
 
if ($num_1 === $num_2) {
    echo "Value is matched using ===";
} else {
    echo "Value is not matched using ===";
}
 
?>

We have compared the two variable one by one by using == and === Operator, we get the following result.

Tutorials Class - Output Window

Value matched using ==
Now we will check using === operator
Value is not matched using ===

You will see that value is matched if used the equal operator '==‘ and not matched if used identical operator '===' because data type is not same for both numbers.

Therefore, if we need to match both values strictly with datatypes, '===' operator will be used else '==' will be used in PHP.

What is the difference between GET and POST method in PHP?

HTTP

The Hypertext Transfer Protocol (HTTP) is designed to enable communications between clients and servers.

HTTP works as a request-response protocol between a client and server.

A web browser may be the client, and an application on a computer that hosts a web site may be the server.

A client (browser) submits an HTTP request to the server; then the server returns a response to the client.

A client (browser) submits an HTTP request to the server; then the server returns a response to the client. The response contains status information about the request and may also contain the requested content.

There are two ways the browser client can send information to the web server.
GET – Requests data from a specified resource
POST – Submits data to be processed to a specified resource


GET Method

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character.

http://www.tutorialsclass.com/index.htm?name1=value1&name2=value2

GET requests can be cached
GET requests remain in the browser history
GET requests can be bookmarked
GET requests should never be used when dealing with sensitive data
GET requests have length restrictions
GET requests should be used only to retrieve data

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of PHP GET method</title>
</head>
<body>
<?php
if(isset($_GET["name"])){
    echo "<p>Hi, " . $_GET["name"] . "</p>";
}
?>
<form method="get" action="<?php echo $_SERVER["PHP_SELF"];?>">
    <label for="inputName">Name:</label>
    <input type="text" name="name" id="inputName">
    <input type="submit" value="Submit">
</form>
</body>

POST Method

The POST method transfers information via HTTP headers. The information is encoded as described in case of GET method and put into a header called QUERY_STRING.

The POST method does not have any restriction on data size to be sent.

The POST method can be used to send ASCII as well as binary data.

The data sent by POST method goes through HTTP header so security depends on HTTP protocol. By using Secure HTTP you can make sure that your information is secure.

The PHP provides $_POST associative array to access all the sent information using POST method.

<!DOCTYPE html>
<html lang="en">
<head>
    <title>Example of PHP POST method</title>
</head>
<body>
<?php
if(isset($_POST["name"])){
    echo "<p>Hi, " . $_POST["name"] . "</p>";
}
?>
<form method="post" action="<?php echo $_SERVER["PHP_SELF"];?>">
    <label for="inputName">Name:</label>
    <input type="text" name="name" id="inputName">
    <input type="submit" value="Submit">
</form>
</body>

Advantages and Disadvantages of Using the GET Method

Since the data sent by the GET method are displayed in the URL, it is possible to bookmark the page with specific query string values.
The GET method is not suitable for passing sensitive information such as the username and password, because these are fully visible in the URL query string as well as potentially stored in the client browser’s memory as a visited page.
Because the GET method assigns data to a server environment variable, the length of the URL is limited. So, there is a limitation for the total data to be sent.


GET vs. POST

GETPOST
BACK button/ReloadHarmlessData will be re-submitted (the browser should alert the user that the data are about to be re-submitted)
BookmarkedCan be bookmarkedCannot be bookmarked
CachedCan be cachedNot cached
Encoding typeapplication/x-www-form-urlencodedapplication/x-www-form-urlencoded or multipart/form-data. Use multipart encoding for binary data
HistoryParameters remain in browser historyParameters are not saved in browser history
Restrictions on data lengthYes, when sending data, the GET method adds the data to the URL; and the length of a URL is limited (maximum URL length is 2048 characters)No restrictions
Restrictions on data typeOnly ASCII characters allowedNo restrictions. Binary data is also allowed
SecurityGET is less compared to POST data sent is part of URLPOST is a little safer than GET because the parameters are not stored in browser history or in web server logs
VisibilityData is visible to everyone in the URLData is not displayed in the URL

How do you split a string into an array?

PHP explode() function is used to split the string into an array based on a certain character, substring or a symbol.

In this example, we have a string containing language list separated by a comma. Therefore, we can pass a comma character as a delimiter to break the string into the array.

<?php
// Take a string containing language list separated by a comma
$string = "PHP, HTML, CSS, JavaScript, MySQL";

// Use PHP explode function to extract all names separated by comma
$name_array = explode(",", $string);

// print array
print_r($name_array);
?>

Run example: https://paiza.io/projects/fXWTx9TVtj1FFvQPw75Wyg

Tutorials Class - Output Window

Array
(
[0] => PHP
[1] => HTML
[2] => CSS
[3] => JavaScript
[4] => MySQL
)

How to Change Time Zone Settings in PHP?

UTC is the default timezone for PHP on the most server. The date_default_timezone_set() function can be used to update the default timezone for all PHP date/time functions.

You can find List of supported Timezones here

Example: Set default timezone using PHP function.

<?php
date_default_timezone_set("America/New_York");
echo date_default_timezone_get();
?>

Example: Set default timezone using php.ini

date.timezone = America/Los_Angeles

How to Get the Current Year using PHP?

You can easily get current year and time using PHP built-in date() function.

<?php  
// Get current year in PHP
$current_year = date("Y");
echo $current_year;
?> 

This most common use of displaying the current year (dynamically) is inside the copyright message. For example, you must have seen in website footer: Copyright 2020 – Website brand-name.

What is fopen function PHP?

PHP fopen() is inbuilt function which is used to open a file or an URL.

<?php
$file_handle = fopen("sample-file.txt", "w");
?>

This function return FALSE and an error if fails to open a file.