PHP Interview Questions
Last Updated by Pooja Chikara
1 14313
Let's confess, facing an interview is never easy. The whole idea of sitting in a new organization's environment in front of an interviewer gives chills down the spine.
While being interviewed, numerous thoughts pop in your mind, you are anxious, and at the same time, you are also trying hard to focus on the PHP Interview Questions fired at you. Tug of war is always ON between the nervousness and focus you required the most to crack the interview.
Though I can only advise you to stay calm during interviews, one thing on which I can genuinely help you is with your preparation for PHP interviews. I have curated a list of PHP Interview Questions and Answers for all levels.
Technical interviews are very tricky, especially the ones which involve real-time coding. These interviews demand various aspects that have to be taken care of by the candidate. This list of Top PHP Interview Questions and Answers will fulfil all your preparation needs.
With this blog on PHP Interview Question, I have taken care of all aspects. This blog can help you in brushing up your PHP skill. All the answers are well explained with the fundamentals.
You will find all the basic code and the output you can retain while appearing in PHP interviews. These advanced questions will benefit both freshers and experienced candidates.
Top 50 PHP Interview Questions
1 What is PHP and What is its use.?
PHP stands for Hypertext Preprocessor. It is one of the most popular server-side languages, which means it runs on the webserver. It is used to add functionality to the web-pages, which HTML alone cannot add.
PHP is used to make static as well as dynamic web-pages. PHP adds enhanced user interaction functionality as well as it interacts with SQL databases essential for web sites.
2 Explain the difference b/w static and dynamic websites?
Static websites are the collection of static web pages that contain the data that is not changed according to user interaction and usually written in HTML. The content of static websites is equal for every user.
On the other hand, dynamic websites contain dynamic web pages, which means dynamic websites can change content according to user interaction. These types of websites require a database and server-side scripting languages along with plain HTML.
3 What are the popular Content Management Systems (CMS) in PHP?
CMS stands for Content Management System, which allows users to create and modify websites without any programming knowledge.
WordPress is the most popular CMS nowadays. Joomla, Drupal, Shopify, Magento are some other popular CMS.
4 How can we directly display output to the browser?
We can directly display the output to the browser with the short tag () without any output method.
According to PHP version 5.4.0, we can use this tag directly without making any change in php.ini file. But as of PHP version 7.0, this tag is removed from PHP, and we need to enable this tag before using it.
5 What are the popular frameworks in PHP?
PHP frameworks streamline the development of web applications written in PHP by providing an essential structure to build the web application; in other words, PHP framework provides a quick pattern to developing websites. These frameworks follow the MVC pattern. It divides the whole code into three parts as: Modal, View and Controller.
Modal: Represents the backend details and other data.
View: Interacts with the user and serves user requests.
Controller: Works as a mediator between view and modal.
Some most popular PHP frameworks are:
- Laravel
- CodeIgniter
- Symfony
- Zend
- Phalcon
- CakePHP
- Yii
- FuelPHP
6 List some of the features of PHP7.
1. Scalar type declaration: in PHP, we can declare the type of only two data types at declaration time 1. Array, and 2. Object of the class. But in PHP 7, we can declare the type of any data type.
2. Return type declaration: Return type declaration represents the declaration of the type of value to be returned from a function.
In PHP 7, we can declare the type of value to be returned by function.
3. Null Coalescing Operator: null coalescing operator is ??. It used as an alternative of the isset() method along with a ternary operator. It returns the first operand if the value given in condition exists and not NULL otherwise second operand returned.
4. Spaceship Operator: the spaceship operator represents by <=>.
It used to compare two expressions and returns 0 if values are equal, -1 if the first value is less than from second and 1 if first value greater than from second.
5. Constant arrays using define(): in PHP 7, we can define constants with the help of define() method.
Example:
define('php interview questions', array('Top 10','Top 20','Top 30'));
7 What is the difference between "echo" and "print" in PHP?
echo | |
echo is not a kind of function, it is a language construct, hence, you can use it with or without parentheses such as echo or echo(). It do not return any value. | On the other hand print is not a function. It is also a language construct like echo but it is always return a value either 0 or 1 so, we can use it to print the result of any regular expression. |
With the help of echo, we can display the value of a variable, string with single quotes or with double quotes and multiple strings separated by commas. | As compared to echo, the execution of print is slow. It can display only one string at a time. |
Code:
<?php $myString1 = " php interview questions "; $myString2 = ' php interview questions and answers for experienced '; echo $myString1.'<br>'; // displaying data with echo print($myString2); // displaying data using print ?>
8 What is meant by variable in PHP?
In PHP, we can use the value stored in one variables as a name of another variable. This is known as variable variables and denoted by $$. See the code to understand.
Code:
<?php $var1 = "php_interview_questions"; $$var1 = 'top_20'; echo $var1."<br>"; echo $$var1; ?>
Output:
9 What are different types of arrays and how can you declare the array in PHP?
An array is a data structure that stores one or more values of related data in a single variable. For instance, if you want to store 100 numbers, then instead of creating 100 variables, you can define array with length of 100. It is a convenient way to store data.
There are three different types of arrays and each array value is accessed using an ID, which is known as array index.
Numeric array - An array with a numeric index. It stores and accesses the values in linear form.
Associative array - An array with strings as index. This stores element values in the association with key values rather than in a strict linear index order.
Multidimensional array - An array containing one or more arrays and values is accessed using numerous indices.
These can be declared with the help of an array() constructor.
$fruits = array( 'a'=>'apple', 'b'=>'mango', 'c'=>'banana3', 'd'=>'grapes' );
10 Explain some of the PHP string functions.
PHP Strings is very interesting part in PHP and it is one of the most used data type in PHP.
A PHP string can be a series of letters, numbers, special characters and arithmetic values. It can also be a combination of all. A quotation mark (‘’) is used to define the string and is encloses the string characters.
Here are some of the frequently used string functions:
A. PHP String Length Function: strlen()
The PHP strlen() function returns the length of string. It is an inbuilt function of PHP.
Code:
<?php $str="John and Sean are best friends"; $length=strlen($str); echo "The length of the given string is : <strong>$length</strong>"; ?>
Output:
Learn more about strlen() function.
B. PHP String Position Function: strpos()
strpos() function of PHP is used to search a particular piece of text in a string and returns the first occurrence of that text. It is an inbuilt function of PHP.
Code:
<?php $str="John and Sean are best friends"; $search="best"; $res=strpos($str,$search); echo "The first occurrence of the best in the given string is : <strong>$res</strong>"; ?>
Output:
Learn more about strpos() function.
C. PHP Strings - Replace text
str_replace() function of PHP is used to replace the part of a string with another string. It is an inbuilt function of PHP.
Code:
<?php $str="PHP interview Questions and answers for freshers"; $find="freshers"; $replace="experienced"; $mod_str=str_replace($find,$replace,$str); echo "Old string is :<strong>$str</strong><br>"; echo "After replacement string is :<strong>$mod_str</strong>"; ?>
Output:
Learn more about str_replace() function.
11 What are the uses of explode() and implode() functions?
Implode(): PHP implode() function is used to join elements of an array with a string. It returns a string from elements of an array. In other words it creates a large string from an array of small strings.
The first argument is the separator of delimiter which will be placed in the elements of the second argument.
For example:
<?php $array=array(12,14,23.22,45); $mul=array_product($array); echo "Product of given array is: <strong>$mul</strong>"; ?>
Output:
Explode(): If you have a string and want to split that string into array of values, you can use explode function. Explode function is used to break a string into array. It is just contradiction of implode function. It breaks the string into small texts which you define in the separator.
The first argument is the string containing the field separator and the second argument is the string itself which we need to split.
For example:
<?php $getdata= "Men-Women-Shirts-Kitchen-Books-Formal Dresses"; $final_string= explode('-', $getdata); print_r ($final_string); ?>
Output:
12 Write a code of reverse a string (word wise) in PHP.
With the help of explode and array_reverse function of PHP, we can reverse a string words wise.
Code:
<?php $s = "php interview questions and answers"; // break the string up into words $words = explode(' ',$s); // reverse the array of words $words = array_reverse($words); // rebuild the string $s = implode(' ',$words); print $s; ?>
13 What is the meant by 'passing the variable by value and reference' in PHP?
Generally, we pass a variable in function by two types either by value or by reference.
Passing the variable by value: In this method, we pass the value of the variable as a parameter in the function.
Code:
<?php function php_example($a, $b) { print "$a <br>"; print "$b"; } php_example('php interview questions','php interview questions and answers'); ?>
Output:
1. Passing by reference
In this method, we pass the address or reference of the variable as a parameter in the function.
Code:
<?php function f1($param){ //passing variable by value $param ++; } function f2(&$param){ // passing by reference $param ++; } $x=100; f1($x); echo $x."<br>"; // value of $x does not change so return 100 f2($x); echo $x; // return 101 here ?>
Output:
14 What is type casting and type juggling? Explain by giving examples.
Typecasting:
In typecasting, we change the data type of variable.
Example:
<?php $var1=1234.222; $res1=$var1; $res2=(int)$var1; echo $res1; // return original value of variable echo "<br>"; echo $res2; // only integer part of the variable print by this line ?>
Output:
Type juggling:
In PHP, we do not need to declare the data type of variable at the creation time. PHP automatically set the type of variable when we assign value to it its called type juggling.
Example:
<?php $var1=124; // integer $var2='555'; // string $res1=$var1+$var2; echo $res1; // $var2 will convert into integer by complier before calculation and return the sum ?>
Output:
15 How can you retrieve data from the MySQL database using PHP?
To retrieve data form MYSQL database first we need to make connection with database with the help of the below mentioned command.
$db=mysqli_connect(host, username, password, database);
After establishing the connection with the database, we can access data from database with the help of MYSQL SELECT query.
Example:
<?php // create connection with database $db=mysqli_connect("localhost", "root", "", "test"); // query to retrieve database $query="SELECT email_id FROM user order by id ASC LIMIT 5"; $result=mysqli_query($db,$query); // display retrieved data foreach($result as $row){ echo $row['email_id']."<br>"; } ?>
16 Which function is used in PHP to count the total number of rows returned by any query?
With the help of mysqli_num_rows() function of PHP we can count the total number of rows returned by any query.
Example:
<?php // create connection with database $db=mysqli_connect("localhost", "root", "", "test"); // query to retrive database $query="SELECT email_id FROM user"; $result=mysqli_query($db,$query); // count number of rows $num=mysqli_num_rows($result); echo $num; ?>
17 How can you create a session in PHP?
To create a session in PHP, first we need to start the session then only we can create a session.
Example:
<?php // start session first session_start(); // now create session $_SESSION['demo']="php interview questions and answers for experienced" ; // session demo created successfully. echo $_SESSION['demo']; ?>
18 How can you upload a file using PHP?
With the help of move_uploaded_file() function of a variable, we can upload a file.
Example:
<?php if(isset($_POST['f_submit'])){ name=$_FILES['file']['name']; $tempname=$_FILES['file']['tmp_name']; $a=move_uploaded_file($tempname,'upload/'.name); if($a){ echo "uploaded successfully"; }else{ echo "Try again"; } } ?> <form method="post" action="" enctype="multipart/form-data"> <input type="file" name="file" /> <input type="submit" name="f_submit" value="Upload" /> </form>
Output:
Choose file and click on upload button.
19 How to include a file to a PHP page?
Include() and require() functions are used to put the contents of a file with PHP source code into another file.
The key difference between these function is that if an error occurs include() will produce a warning and the script will continue to run. Whereas in case of require() if an error occurs, it will stop the execution of script.
include("file.php"); require("file.php");
20 What is the difference between abstract class and interface?
The key differences between an interface and an abstract class are:
a) All the functions declared in an interface are inherently public and abstract whereas functions in abstract class must be declared as public and abstract where required.
b) A child class can only extend a single class, whereas an interface can extend or a class can implement multiple other interfaces.
c) To use an abstract class, a concrete class must extend the abstract class which then makes all of the methods defined in the abstract available inside the concrete class, whereas interfaces allow you to specify the methods which a class must implement, without having to define how these methods are implemented.
21 How can we submit a form without a submit button?
With the help of JavaScript and jQuery, we can submit form without any submit button.
Javascript code:
document.getElementById("form_id").submit();
jQuery code:
$('#form_id').submit();
Here form_id represents the id of the form which we want to submit.
22 What is the role of Ksort() in PHP?
PHP ksort() function is used to sort an associative PHP array. You can sort the array as per your preferences.
This function sorts the array according to the keys.
Ksort(): Sort array by keys in an ascending order.
Krsort(): Sort array by keys in descending order.
uKsort(): Sort array by keys in user-defined order.
Example:
<?php $arr=array("php"=>"22","interview"=>"1","questions"=>"11","and"=>"150","answers"=>"15"); ksort($arr); echo "<pre>"; print_r($arr); ?>
Output:
Note: In order to sort array by values assort() is used.
23 How to get the value of current session id?
With the help of session_id() PHP function we can get the value of current session id. This function returns current session id on success and empty string on failure.
24 What are the functions of the header() function in PHP?
header() function of PHP is used to send raw HTTP header to client. It is an inbuilt function of PHP. Here HTTP stands for Hyper Text Transfer Protocol.
This protocol is responsible for communication between web clients and server by sending HTTP requests and receive HTTP responses.
Example:
<?php header("location:https://www.codingtag.com"); exit(); ?>
This code will redirect to your page on https://www.codingtag.com
Note: To prevent some unexpected behaviour, use of either exit() function or die() function is required after the use of header() function.
I hope your these PHP interview Questions and Answers are helping you in brushing up your PHP fundamentals. Let's learn some advanced questions to raise our level of preparation.
25 What is multiple inheritance? Are multiple inheritances supported in PHP?
Multiple inheritance is one of the most important property of OOPS concepts. It is the mechanism in which the child class or sub-class can inherit the property of multiple parent class or super class.
PHP does not support multiple inheritance. By using PHP interfaces or PHP traits we can implement multiple inheritance in PHP.
26 What are Traits?
Since PHP does not support multiple inheritance, PHP traits comes handy in such situations. A trait allows you to reuse the set of methods in many various classes which need not to be in the same class hierarchy. A class can use multiple traits.
<?php // implementing multiple inheritance in PHP traits // creating a trait1 trait myTrait1 { public function trait1_function() { echo "I am inside trait1.<br>"; } } // creating a trait2 trait myTrait2 { public function trait2_function() { echo "I am inside trait2<br>"; } } // creating a class class myClass{ use myTrait1; use myTrait2; } $obj = new myClass(); $obj->trait1_function(); $obj->trait2_function(); ?>
Output:
27 What is meant by public, private, static and final scopes?
Access modifiers are basically PHP Keywords which set the accessibility of the variables and methods. We can also set the accessibility of variables and functions of a class by setting the accessibility of class.
1. Public: This keyword used to make variables and functions accessible to anywhere means we can access either inside a class or anywhere outside the class.
2. Protected: This keyword used to make variables and functions accessible into that class and its child or derived classes.
3. Private: This keyword used to make variables and functions accessible only into that class means we can't access private properties outside the class.
4. Static: This keyword is used to make functions accessible without creation of the object. We can access static function by class name and static variables has the existence before the throughout the execution of the script.
5. Final: This keyword is used to add some extra restriction on the PHP class. The final class cannot be inherited by other class.
28 Which functions are used to remove whitespaces from the string?
In PHP we have 3 inbuilt methods to remove extra whitespaces from the string.
a) trim(): This function of PHP is used to remove the user defined text or whitespaces from both side of a PHP string. It is an inbuilt function in PHP. Return type of this function is string.
b) ltrim(): This function of PHP is used to remove some user-defined characters or white space from the left side of a PHP string. It is an inbuilt function of PHP. The return type of this function is a string.
c) rtrim(): This function is used to remove the user-defined text or whitespaces from the right side of a string. It is an inbuilt function in PHP. The return type of this function is a string.
29 What type of errors can be occurred in PHP?
In PHP many predefined errors are present and are known as built in errors. Every predefined error has own value i.e. E_NOTICE predefined error value is 8, E_USER_WARNING value is 512, E_USER_NOTICE value is 1024, E_ALL value is 8191.
For example:
- E_NOTICE
- E_ERROR
- E_WARNING
- E_USER_ NOTICE
- E_CORE_ERROR
- E_CORE_WARNING
- E_USER_ERROR
- E_USER_WARNING
- E_COMPILE_RROR
- E_COMPILE_WARNING
- E_PARSE
- E_ALL
To handle this types of errors we can create own function. Function name is error_handling_function($error_number, $error_string) and we can use an inbuilt handler function set_error_handler().
Example:
<?php // defined error handler function function error_handling_function($error_number, $error_string) { echo "<td>Error:</td> [$error_number] $error_string"; } // set error handler function are used set_error_handler("error_handling_function"); echo($ErrorTrigger); ?>
Output:
30 What is the difference between mysql_pconnect. mysql_connect?
Both mysql_connect() and mysql_pconnect() are used to establish a connection with mysql database. The key difference is that mysql_pconnect() makes a persistent connection with database which means that the connection establishes only single time and works throughout the working.
On the other hand mysql_connect() create connection with every single query executed with database and closes the connection after the execution of every query.
31 How comparisons of objects are done in PHP5?
With the help of PHP comparison operator (==) and identity operator (===), we can make a comparison between two PHP objects.
Comparison operator (==) returns true if two objects contain same attributes and the values along with related to the same class on the other hand identity operator (===) return true if two objects belong to same instance of a class.
32 Explain PHP variable length argument function?
PHP provide the facility to declare variable length argument in a function which means that a function can contains n number of arguments by adding three dots (…) before the variable name.
Example:
<?php function mul(...$var) { $res = 1; foreach ($var as $num) { $res=$res*$num; } return $res; } echo 'Multiplication is :'.mul(2,4,6,8); ?>
Output:
33 What is the method to register a variable into a session?
You can register a variable into session using session_register().
Example:
<?php Session_register($ur_session_var); ?>
34 Write syntax to open a file in PHP?
fopen() function of PHP is used to open a file or a URL. By default, it attempts to create a file with permission 0666 (rw-rw-rw-) return type of this function is Boolean means it returns TRUE on success and FALSE with error messages on failure.
Syntax:
Parameter Description:
1. : represents the file or URL which to be open by this function. It is mandatory.
2. $mode: represents the access type necessary for file or stream. It is also mandatory. It have 11 possible values.
3. $include_path: represents the search for the file in the include_path in the php.ini file. It is an optional parameter. Sets it s value to 1 for the search explained above.
4. $context: represents the context of file handle. It is also an optional parameter.
Example:
This example open file desti.txt and read its data and display on the page. Create a file name as desti.txt and put the content mentioned below in that file.
desti.txt
Welcome to Coding Tag
span style="background-color: rgb(239, 239, 239);">You are brushing up with Top PHP interview Questions and Answers.
Code:
<?php =fopen("desti.txt","r"); // open file in read mode echo fread(,filesize("desti.txt")); // read content on desti.txt fclose(); ?>
Output:
35 How can we increase execution time of a PHP script?
By using ini_set() PHP function we can increase execution time of a PHP script.
For better result we should add this function at the top of the top of the script.
ini_set('max_execution_time', 60); // 60 (seconds) = 1 Minutes ini_set('max_execution_time', 0); // 0 = Unlimited
36 What is htaccess in PHP? How you can delay htaccess?
.htaccess acts as a configuration file that permits configuration modifications on a per-directory basis.
ini_set('max_execution_time', 0); // 0 = UnlimitedSteps to deny direct access through .htaccess
Create .htaccess file on the website.
You just need to copy and paste the following simple code in your .htaccess file.
# directory browsing Options All -Indexes
37 What is the use of the function imagetypes?
imagetypes() function is used to return the supported image type in PHP. it is an inbuilt function of PHP.
Example:
<?php if (imagetypes() & IMG_JPG) { echo "SUPPORTED"; } else { echo "NOT SUPPORTED"; } ?>
38 What are the various properties of image and how to retrieve them?
There are various properties of images such as: image type, image width, and height, created date and last modified date etc.
In PHP, we can retrieve these properties with the help of some inbuilt functions.
- imagesx():This function used to retrieve the width of image.
- imagesy(): This function used to retrieve the height of image.
- getimagesize(): This function returns width, height, image type and mime of the image.
39 What are constructor and destructor in PHP?
Constructor: It is a method of class which basically used to initialize the object of that class and assigns the values to the properties of objects.
Syntax:
Destructor: It is used to destroy the objects of a class. It free the memory acquired by the objects of class.
Syntax:
Example:
<?PHP class demo { function __construct() { echo "we are inside the constructor.<br>"; } function __destruct() { echo 'Destroying The object: ', PHP_EOL; } } $obj= new demo(); ?>
40 What is the difference between GET and POST method in PHP?
GET and POST both are HTTP methods which are used to enable communication between clients and server. They both are to send form data to the server.
GET: This method sends the form data in the form of query string which shows into the UR. GET carries request parameter appended in URL string making it unsecure form of communication We can send a limited amount of data through it.
POST: This method send the data in the form of HTTP requests and data is send in the message body making it more secure way to send data. There is no length restriction like GET.
41 What is the use of callback in PHP?
As the name describe, a callback is a PHP function which passed as an argument into other PHP function.
<?php // callback function function myCallbackFunction() { echo "php interview questions and answers"; } call_user_func('myCallbackFunction'); ?>
42 What is a lambda function in PHP?
A lambda function is also known as anonyms function. It used to passed as an argument into other PHP function. We can store it in a variable and pass variable into other methods.
Example:
<?php function multi($x,$y) { return $x*$y; }; function result($res){ echo "The result is: $res"; } result(multi(5,5)); ?>
43 What is the maximum length of a table name, a database name, or a field name in MySQL?
In PHP, The maximum length of a tale name, database name or a field name is 64 characters.
44 How can we take a backup of a mysql table and how can we restore it?
To take a backup of a mysql table the following query is used.
mysqldump db_name table_name | gzip > table_name.sql.gz
To restore back table into database the following line is used.
gunzip < table_name.sql.gz | mysql -u username -p db_name
45 How can we encrypt the username and password using PHP??
With the help of md5() function of PHP, we can encrypt the password and improve the security of our website.
Example:
<?php $str="php interview questions and answers"; $enc_str=md5($str); echo "The original string is: <strong>$str</strong><br>"; echo "The encrypted string is: <strong>$enc_str</strong>"; ?>
46 How do I find out the number of parameters passed into function?
With the help of PHP func_num_args() function, we can get the number of parameters passed into a function.
Example:
<?php $str="php interview questions and answers"; $enc_str=md5($str); echo "The original string is: <strong>$str</strong><br>"; echo "The encrypted string is: <strong>$enc_str</strong>"; ?>
47 How would you sort an array of strings to their natural case-insensitive order, while maintaining their original index association?
With the help of PHP natcasesort() function, we can sort an array of strings to their natural case-insensitive order.
Example:
<?php $str="php interview questions and answers"; $enc_str=md5($str); echo "The original string is: <strong>$str</strong><br>"; echo "The encrypted string is: <strong>$enc_str</strong>"; ?>
48 What is the difference between runtime exception and compile time exception?
When an error occurs at runtime then the exception thrown is called runtime exception for example: division by zero, array index out of range etc.
On the other hand compile time exception is thrown when there is some logical error into the piece of code. For example: missing terminator or parenthesis, variable declaration error etc.
49 Which PHP global variable is used for uploading a file?
With the help of $_FILES PHP global variable we can upload a file in php.
I hope that this list of Top PHP interview Questions and Answers will help you with your preparation and you will be able to brush up your fundamentals for appearing in a PHP interview.
Please leave your comments in the box below and Share and Like this page. It will really boost our morale to write better for you
All The Best for your Interview
Share:
Sanket Jan 22, 2019
Good mam so usefull