61+ PHP Interview Questions And Answers 2020

Spread the love

Table of Contents

PHP Interview Questions And Answers for Freshers &  Experienced 2020

What is PHP?

PHP is likely one of the in style server-side scripting languages for growing an internet software. The full type of PHP is Hypertext Preprocessor. It is utilized by embedding HTML for creating dynamic content, speaking with a database server, dealing with periods, and so forth.

Why will we use PHP?

There are a number of advantages of utilizing PHP. First of all, it’s completely free to make use of. So anybody can use PHP with none price and host the location at a minimal price.

It helps a number of databases. The mostly used database is MySQL which can be free to make use of. Many PHP frameworks are used now for net growth, corresponding to CodeIgniter, CakePHP, Laravel, and so forth. These frameworks make the net growth process a lot simpler than earlier than.

Is PHP a strongly typed language?

No. PHP is a weakly typed or loosely typed language. This means PHP doesn’t require to declare knowledge varieties of the variable while you declare any variable like the opposite normal programming languages C# or Java. When you retailer any string worth in a variable, then the info sort is the string and when you retailer a numeric worth in that very same variable then the info sort is an Integer.

Sample code:

$var = “Hello”; //String
$var = 10; //Integer

PHP Interview Questions

What is supposed by variable variables in PHP?

When the worth of a variable is used because the title of the opposite variables then it’s known as variable variables. $$ is used to declare variable variables in PHP.

Sample code:

$str = “PHP”;
$$str = ” Programming”; //declaring variable variables
echo “$str ${$str}”; //It will print “PHP programming”
echo “$PHP”; //It will print “Programming”

What are the variations between echo and print?

Both echo and print methodology print the output within the browser however there’s a distinction between these two strategies.

echo doesn’t return any worth after printing the output and it really works sooner than the print methodology. print methodology is slower than the echo as a result of it returns the boolean worth after printing the output.

Sample code:

echo “PHP Developer”;
$n = print “Java Developer”;

How are you able to execute PHP script from the command line?

You have to make use of PHP command within the command line to execute a PHP script. If the PHP file title is take a look at.php then the next command is used to run the script from the command line.

php take a look at.php

How are you able to declare the array in PHP?

You can declare three varieties of arrays in PHP. They are numeric, associative and multidimensional arrays.

Sample code:

//Numeric Array
$laptop = array(“Dell”, “Lenavo”, “HP”);
//Associative Array
$colour = array(“Sithi”=>”Red”, “Amit”=>”Blue”, “Mahek”=>”Green”);
//Multidimensional Array
$programs = array ( array(“PHP”,50), array(“JQuery”,15), array(“AngularJS”,20) );

What are the makes use of of explode() and implode() capabilities?

explode() operate is used to separate a string into an array and implode() operate is used to make a string by combining the array components.

Sample code:

$textual content = “I like programming”;
print_r (explode(” “,$textual content));
$strarr = array(‘Pen’,’Pencil’,’Eraser’);
echo implode(” “,$strarr);

PHP Developer Interview Questions

Which operate can be utilized to exit from the script after displaying the error message?

You can use exit() or die() operate to exit from the present script after displaying the error message.

Sample code:

exit(” Unable to open the file”);
Sample code:

die(” Unable to connect with the database”);

Which operate is utilized in PHP to verify the info sort of any variable?

gettype() operate is used to verify the info sort of any variable.

Sample code:

echo gettype(true).”; //boolean
echo gettype(10).”; //integer
echo gettype(‘Web Programming’).”; //string
echo gettype(null).”; //NULL

How are you able to enhance the utmost execution time of a script in PHP?

You want to vary the worth of the max_execution_time directive within the php.ini file for growing the utmost execution time.

For Example, if you wish to set the max execution time for 120 seconds, then set the worth as follows,

max_execution_time = 120

PHP Interview Questions For Freshers

What is supposed by ‘passing the variable by value and reference’ in PHP?

When the variable is passed as value then it is called pass variable by value.

Here, the main variable remains unchanged even when the passed variable changes.

Sample code:

function test($n) {

echo $m;
When the variable is passed as a reference then it is called pass variable by reference. Here, both the main variable and the passed variable share the same memory location and & is used for reference.

So, if one variable changes then the other will also change.

Sample code:

function test(&$n) {
echo $m;

Explain type casting and type juggling.

The way by which PHP can assign a particular data type for any variable is called typecasting. The required type of variable is mentioned in the parenthesis before the variable.

Sample code:

$str = “10”; // $str is now string
$bool = (boolean) $str; // $bool is now boolean
PHP does not support datatype for variable declaration. The type of the variable is changed automatically based on the assigned value and it is called type juggling.

Sample code:

$val = 5; // $val is now number
$val = “500” //$val is now string

How can you make a connection with MySQL server using PHP?

You have to provide MySQL hostname, username, and password to make a connection with the MySQL server in mysqli_connect() method or declaring database object of the mysqli class.

Sample code:

$mysqli = mysqli_connect(“localhost”,”username”,”password”);
$mysqli = new mysqli(“localhost”,”username”,”password”);

Core PHP Interview Questions

How can you retrieve data from the MySQL database using PHP?

Many functions are available in PHP to retrieve the data from the MySQL database.

Few functions are mentioned below:

a) mysqli_fetch_array() – It is used to fetch the records as a numeric array or an associative array.

Sample code:

// Associative or Numeric array
echo “Name is $row[0]
echo “Email is $row[’email’]
b) mysqli_fetch_row() – It is used to fetch the records in a numeric array.

Sample code:

//Numeric array
printf (“%s %s\n”,$row[0],$row[1]);
c) mysqli_fetch_assoc() – It is used to fetch the records in an associative array.

Sample code:

// Associative array
printf (“%s %s\n”,$row[“name”],$row[“email”]);
d) mysqli_fetch_object() – It is used to fetch the records as an object.

Sample code:

// Object
printf (“%s %s\n”,$row->name,$row->email);

PHP Technical Interview Questions

What are the differences between mysqli_connect and mysqli_pconnect?

mysqli_pconnect() function is used for making a persistent connection with the database that does not terminate when the script ends.

mysqli_connect() function searches any existing persistence connection first and if no persistence connection exists, then it will create a new database connection and terminate the connection at the end of the script.

Sample code:

$DBconnection = mysqli_connect(“localhost”,”username”,”password”,”dbname”);
// Check for valid connection
if (mysqli_connect_errno())
echo “Unable to connect with MySQL: ” . mysqli_connect_error();
mysqli_pconnect() function is depreciated in the new version of PHP, but you can create a persistence connection using mysqli_connect with the prefix p.

Which function is used in PHP to count the total number of rows returned by any query?

mysqli_num_rows() function is used to count the total number of rows returned by the query.

Sample code:

$mysqli = mysqli_connect(“hostname”,”username”,”password”,”DBname”);
$result=mysqli_query($mysqli,”select * from employees”);

How can you create a session in PHP?

session_start() function is used in PHP to create a session.

Sample code:

session_start(); //Start session
$_SESSION[‘USERNAME’]=’Fahmida’; //Set a session value
unset($_SESSION[‘USERNAME’]; //delete session value

What is the use of imagetypes() method?

image types() function returns the list of supported images of the installed PHP version. You can use this function to check if a particular image extension is supported by PHP or not.

Sample code:

//Check BMP extension is supported by PHP or not
if (imagetypes() &IMG_BMP) {
echo “BMP extension Support is enabled”;

PHP Interview Questions And Answers For Experienced

Which function you can use in PHP to open a file for reading or writing or for both?

You can use fopen() function to read or write or for doing both in PHP.

Sample code:

$file1 = fopen(“myfile1.txt”,”r”); //Open for reading
$file2 = fopen(“myfile2.txt”,”w”); //Open for writing
$file3 = fopen(“myfile3.txt”,”r+”); //Open for reading and writing

What is the difference between include() and require()?

Both include() and require() function are used for including PHP script from one file to another file. But there is a difference between these functions.

If any error occurs at the time of including a file using include() function, then it continues the execution of the script after showing an error message. require() function stops the execution of a script by displaying an error message if an error occurs.

Sample code:

if (!include(‘test.php’)) echo “Error in file inclusion”;
if (!require(‘test.php’)) echo “Error in file inclusion”;

Which operate is utilized in PHP to delete a file?

unlink() operate is utilized in PHP to delete any file.

Sample code:


What is the usage of strip_tags() methodology?

strip_tags() operate is used to retrieve the string from a textual content by omitting HTML, XML and PHP tags. This operate has one necessary parameter and one non-compulsory parameter. The non-compulsory parameter is used to simply accept specific tags.

Sample code:

//Remove all tags from the textual content
echo strip_tags(“<b>PHP</b> is a popular <em>scripting</em> language”);
//Remove all tags excluding <b> tag
echo strip_tags(“<b>PHP</b> is a popular <em>scripting</em> language”,”<b>”);

How are you able to ship an HTTP header to the shopper in PHP?

The header() operate is used to ship uncooked HTTP header to a shopper earlier than any output is shipped.

Sample code:

header(‘Location: http://www.your_domain/’);

PHP Interview Questions And Answers

Which capabilities are used to rely the full variety of array components in PHP?

rely() and sizeof() capabilities can be utilized to rely the full variety of array components in PHP.

Sample code:

echo rely($names);
echo sizeof($marks);

What is the distinction between substr() and strstr()?

substr() operate returns part of the string primarily based on the place to begin and size. Length parameter is non-compulsory for this operate and whether it is omitted then the remaining a part of the string from the place to begin will probably be returned.

strstr() operate searches the primary prevalence of a string inside one other string. The third parameter of this operate is non-compulsory and it’s used to retrieve the a part of the string that seems earlier than the primary prevalence of the looking string.

Sample code:

echo substr(“Computer Programming”,9,7); //Returns “Program”
echo substr(“Computer Programming”,9); //Returns “Programming”
Sample code:

echo strstr(“Learning Laravel 5!”,”Laravel”); //Returns Laravel 5!
echo strstr(“Learning Laravel 5!”,”Laravel”,true); //Returns Learning

How are you able to add a file utilizing PHP?

To add a file through the use of PHP, you must do the next duties.

(i) Enable file_uploads directive

Open php.ini file and discover out the file_uploads directive and make it on.

file_uploads = On
(ii) Create an HTML type utilizing enctype attribute and file ingredient for importing the file.

<type motion=”upload.php” methodology=”post” enctype=”multipart/form-data”>
<enter sort=”file” title=”upd” id=”upd”>
<enter sort=”submit” worth=”Upload” title=”upload”>
(iii) Write a PHP script to add the file

if (move_uploaded_file($_FILES[“upd”][“tmp_name”], “Uploads/”)) {
echo “The file “. basename( $_FILES[“upd”][“name”]). ” is uploaded.”;
} else {
echo “There is an error in uploading.”;

PHP Basic Interview Questions

How are you able to declare a continuing variable in PHP?

outline() operate is used to declare a continuing variable in PHP. Constant variable declares with out the $ image.

Sample code:


Which operate is utilized in PHP to look a selected worth in an array?

in_array() operate is used to look a selected worth in an array.

Sample code:

$languages = array(“C#”, “Java”, “PHP”, “VB.Net”);
if (in_array(“PHP”, $languages)) {
echo “PHP is in the list”;
else {
echo “php is not in the list”;

What is the usage of the $_REQUEST variable?

The $_REQUEST variable is used to learn the info from the submitted HTML type.

Sample code:

Here, the $_REQUEST variable is used to learn the submitted type area with the title ‘username’. If the shape is submitted with none worth, then it’s going to print as “Name is empty”, in any other case it’s going to print the submitted worth.

if (isset($_POST[‘submit’])) {
// acquire worth of enter area
$title = $_REQUEST[‘username’];
if (empty($title)) {
echo “Name is empty”;
} else

<type methodology=”post” motion=”#”>
Name: <enter sort=”text” title=”username”>
<enter sort=”submit” title=”submit”>
<?php ?>

Advanced PHP Interview Questions

What is the distinction between for and Foreach loop in PHP?

For loop is especially used for iterating a pre-defined variety of occasions and Foreach loop is used for studying array components or MySQL consequence set the place the variety of iteration might be unknown.

Sample code:

//Loop will iterate for five occasions
for ($n = 0; $n <= 5; $n++) {
echo “The number is: $n <br>”;
Sample code:

//Loop will iterate primarily based on array components
$elements = array(“HDD”, “Monitor”, “Mouse”, “Keyboard”);
foreach ($elements as $worth) {
echo “$value <br>”; }

How lengthy does a PHP session final for?

By default, session knowledge will final for 24 minutes or 1440 seconds in PHP. But if you would like, you possibly can change the length by modifying the worth of gc_maxlifetime directive in php.ini file. To set the session time for 30 minutes, open php.ini file and set the worth of gc_maxlifetime directive as follows,
gc_maxlifetime = 1800

What is the distinction between “= =” and “= = =” operators.

“= = =” is known as strictly equal operator that’s used to verify the equivalency of two values by evaluating each knowledge sorts and values.

Sample code:

10 and “10” are equal by values however usually are not equal by knowledge sort. One is a string and one is a quantity. So, if the situation will probably be false and print “n is not equal to 10”.

$n = 10;
if ($n === “10”)
echo “n is equal to 10”;
echo “n is not equal to 10”; //This will print

PHP Interview Questions For Experienced

Which operator is used to mix string values in PHP?

Two or extra string values might be mixed through the use of ‘.’ operator.

Sample code:

$val1 = “Web “;
$val2 = “Development”;
echo $val1.$val2; // The output is “Web Development”

What is PEAR?

The full type of PEAR is “PHP Extension and Application Repository”.

Anyone can obtain reusable PHP parts through the use of this framework at a freed from price. It comprises various kinds of packages from completely different builders.

Website: PEAR

What sort of errors might be occurred in PHP?

Different sort of errors can happen in PHP.

Some main error sorts are talked about beneath:

Fatal Errors– The execution of the script stops when this error happens.
Sample code:

In the next script, f1() operate is said however f2() operate is known as which isn’t declared. The execution of the script will cease when f2() operate will name. So, “Testing Fatal Error” is not going to be printed.

operate f1()
{ echo “function 1”;
echo “Testing Fatal Error”;
Parse Errors– This sort of error happens when the coder makes use of a improper syntax within the script.
Sample code:

Here, semicolon(;) is lacking on the finish of the primary echo assertion.

echo “This is a testing script<br/>”
echo “error”;
Warning Errors- This sort of error doesn’t cease the execution of a script. It continues the script even after displaying the error.
Sample code:

In the next script, if the take a look at.txt file doesn’t exist within the present location then a warning message will show to indicate the error and print “Opening File” textual content by persevering with the execution.

$handler = fopen(“test.txt”,”r”);
echo “Opening File”;
Notice Errors- This sort of error exhibits a minor error of the script and continues the execution after displaying the error.
Here, the variable, $a is outlined however $b shouldn’t be outlined. So, a discover of the undefined variable will show for “echo $b” assertion and print “Checking notice error” by persevering with the script.

Sample code:

$a = 100;
echo $b;
echo “Checking notice error”;

PHP Interview Questions And Answers For Freshers

Does PHP assist a number of inheritances?

PHP doesn’t assist a number of inheritances. To implement the options of a number of inheritances, the interface is utilized in PHP.

Sample code:

Here, two interfaces, Isbn and Type are declared and applied in a category, e book particulars so as to add the function of a number of inheritances in PHP.

interface Isbn
public operate setISBN($isbn);

interface Type
public operate setType($sort);

class bookDetails implements Isbn, Type {
personal $isbn;
personal $sort;
public operate setISBN($isbn)
$this -> isbn = $isbn;
public operate setType($sort)


What are the variations between session and cookie?

The session is a worldwide variable that’s used within the server to retailer the session knowledge. When a brand new session creates the cookie with the session id is saved on the customer’s laptop. The session variable can retailer extra knowledge than the cookie variable.

Session knowledge are saved in a $_SESSION array and Cookie knowledge are saved in a $_COOKIE array. Session values are eliminated routinely when the customer closes the browser and cookie values usually are not eliminated routinely.

PHP Interview Questions And Answers For Experienced Candidates

What is the usage of mysqli_real_escape_string() operate?

mysqli_real_escape_string() operate is used to flee particular characters from the string for utilizing a SQL assertion

Sample code:

$productName = mysqli_real_escape_string($con, $_POST[‘proname’]);
$ProductType = mysqli_real_escape_string($con, $_POST[‘protype’]);

Which capabilities are used to take away whitespaces from the string?

There are three capabilities in PHP to take away the whitespaces from the string.

trim() – It removes whitespaces from the left and proper aspect of the string.
ltrim() – It removes whitespaces from the left aspect of the string.
rtrim() – It removes whitespaces from the appropriate aspect of the string.
Sample code:

$str = ” Tutorials for your help”;
$val1 = trim($str);
$val2 = ltrim($str);
$val3 = rtrim($str);

What is a persistence cookie?

A cookie file that’s saved completely within the browser is known as a persistence cookie. It shouldn’t be safe and is especially used for monitoring a customer for lengthy occasions.

This sort of cookie might be declared as follows,

setccookie (“cookie_name”, “cookie_value”, strtotime(“+2 years”);

How can a cross-site scripting assault be prevented by PHP?

Htmlentities() operate of PHP can be utilized for stopping cross-site scripting assaults.

Which PHP world variable is used for importing a file?

$_FILE[] array comprises all the knowledge of an uploaded file.

The use of assorted indexes of this array is talked about beneath:

$_FILES[$fieldName][‘name’] – Keeps the original file name.
$_FILES[$fieldName][‘type’] – Keeps the file type of an uploaded file.
$_FILES[$fieldName][‘size’] – Stores the file size in bytes.
$_FILES[$fieldName][‘tmp_name’] – Keeps the temporary file name which is used to store the file in the server.
$_FILES[$fieldName][‘error’] – Contains error code related to the error that appears during the upload.

PHP Interview Questions And Answers For 5 Year Experience

What is meant by public, private, protected, static and final scopes?

  • Public: Variables, classes, and methods which are declared public can be accessed from anywhere.
  • Private: Variables, classes and methods which are declared private can be accessed by the parent class only.
  • Protected: Variables, classes, and methods which are declared protected can be accessed by the parent and child classes only.
  • Static: The variable which is declared static can keep the value after losing the scope.
  • Final: This scope prevents the child class to declare the same item again.

How can image properties be retrieved in PHP?

getimagesize() – It is used to get the image size.
exif_imagetype() – It is used to get the image type.
imagesx() – It is used to get the image width.
imagesy() – It is used to get the image height.

What is the difference between abstract class and interface?

Abstract classes are used for closely related objects and interfaces are used for unrelated objects.
PHP class can implement multiple interfaces but can’t inherit a number of summary courses.
Common conduct might be applied within the summary class however not an interface.

What is rubbish assortment?

It is an automatic function of PHP.

When it runs, it removes all session knowledge which aren’t accessed for a very long time. It runs on /tmp listing which is the default session listing.

PHP directives that are used for rubbish assortment embrace:

session.gc_maxlifetime (default worth, 1440)
session.gc_probability (default worth, 1)
session.gc_divisor (default worth, 100)

PHP Programming Interview Questions

Which library is utilized in PHP to do numerous varieties of Image work?

Using the GD library, numerous varieties of picture work might be accomplished in PHP. Image work contains rotating photos, cropping a picture, creating picture thumbnail, and so forth.

What is URL rewriting?

Appending the session ID in each native URL of the requested web page for maintaining the session info is known as URL rewriting.

The disadvantages of those strategies are, it would not enable persistence between the periods and, the person can simply copy and paste the URL and ship it to a different person.

What is PDO?

The full type of PDO is PHP Data Objects.

It is a light-weight PHP extension that makes use of a consistence interface for accessing the database. Using PDO, a developer can simply change from one database server to the opposite. But it doesn’t assist all of the superior options of the brand new MySQL server.

Spread the love