List of Most Frequently Asked Core PHP Interview Questions with detailed Answers and Code Examples for Freshers and Experienced Candidates:
Do you want to learn or test your PHP skills for an interview?
Here in this article, we will discuss some of the most common and frequently asked Core PHP interview questions with detailed answers and code samples.
The demand for PHP jobs is increasing day by day. People who are searching or preparing for PHP jobs, have to face some common questions in the interview.
So, if you are a fresher and if you wish to make your career as a PHP developer or even an experienced professional looking to secure a higher position, then you must read this article to increase your chance to get a PHP job easily and quickly.
Table of Contents:
50 Most Common PHP Interview Questions
Given below is the list of most popular PHP interview questions which are commonly asked in the interviews.
Let’s Explore!!
Q #1) What is PHP?
Answer: PHP is one of the popular server-side scripting languages for developing a web application.
The full form of PHP is Hypertext Preprocessor. It is used by embedding HTML for creating dynamic content, communicating with a database server, handling sessions, etc.
Q #2) Why do we use PHP?
Answer: There are several benefits of using PHP. First of all, it is totally free to use. So anyone can use PHP without any cost and host the site at a minimal cost.
It supports multiple databases. The most commonly used database is MySQL which is also free to use. Many PHP frameworks are used now for web development, such as CodeIgniter, CakePHP, Laravel, etc.
Recommended reading =>> Laravel Database handling
These frameworks make the web development task much easier than before.
Q #3) Is PHP a strongly typed language?
Answer: No. PHP is a weakly typed or loosely typed language.
This means PHP does not require to declare data types of the variable when you declare any variable like the other standard programming languages C# or Java. When you store any string value in a variable, then the data type is the string and if you store a numeric value in that same variable then the data type is an Integer.
Sample code:
$var = "Hello"; //String $var = 10; //Integer
Q #4) What is meant by variable variables in PHP?
Answer: When the value of a variable is used as the name of the other variables then it is called 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"
Q #5) What are the differences between echo and print?
Answer: Both echo and print method print the output in the browser but there is a difference between these two methods.
echo does not return any value after printing the output and it works faster than the print method. print method is slower than the echo because it returns the boolean value after printing the output.
Sample code:
echo "PHP Developer"; $n = print "Java Developer";
Q #6) How can you execute PHP script from the command line?
Answer: You have to use PHP command in the command line to execute a PHP script. If the PHP file name is test.php then the following command is used to run the script from the command line.
php test.php
Q #7) How can you declare the array in PHP?
Answer: You can declare three types of arrays in PHP. They are numeric, associative and multidimensional arrays.
Sample code:
//Numeric Array $computer = array("Dell", "Lenavo", "HP"); //Associative Array $color = array("Sithi"=>"Red", "Amit"=>"Blue", "Mahek"=>"Green"); //Multidimensional Array $courses = array ( array("PHP",50), array("JQuery",15), array("AngularJS",20) );
Q #8) What are the uses of explode() and implode() functions?
Answer: explode() function is used to split a string into an array and implode() function is used to make a string by combining the array elements.
Sample code:
$text = "I like programming"; print_r (explode(" ",$text)); $strarr = array('Pen','Pencil','Eraser'); echo implode(" ",$strarr);
Q #9) Which function can be used to exit from the script after displaying the error message?
Answer: You can use exit() or die() function to exit from the current script after displaying the error message.
Sample code:
if(!fopen('t.txt','r')) exit(" Unable to open the file");
Sample code:
if(!mysqli_connect('localhost','user','password')) die(" Unable to connect with the database");
Q #10) Which function is used in PHP to check the data type of any variable?
Answer: gettype() function is used to check the data type of any variable.
Sample code:
echo gettype(true).''; //boolean echo gettype(10).''; //integer echo gettype('Web Programming').''; //string echo gettype(null).''; //NULL
Q #11) How can you increase the maximum execution time of a script in PHP?
Answer: You need to change the value of the max_execution_time directive in the php.ini file for increasing the maximum execution time.
For Example, if you want to set the max execution time for 120 seconds, then set the value as follows,
max_execution_time = 120
Q #12) What is meant by ‘passing the variable by value and reference’ in PHP?
Answer: 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) { $n=$n+10; } $m=5; test($m); 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) { $n=$n+10; } $m=5; test($m); echo $m;
Q #13) Explain type casting and type juggling.
Answer: 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
Q #14) How can you make a connection with MySQL server using PHP?
Answer: 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");
Q #15) How can you retrieve data from the MySQL database using PHP?
Answer: 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 $result=mysqli_query($DBconnection,$query); $row=mysqli_fetch_array($result,MYSQLI_ASSOC); 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 $result=mysqli_query($DBconnection,$query); $row=mysqli_fetch_array($result); 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 $result=mysqli_query($DBconnection,$query); $row=mysqli_fetch_array($result); 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 $result=mysqli_query($DBconnection,$query); $row=mysqli_fetch_array($result); printf ("%s %s\n",$row->name,$row->email);
Q #16) What are the differences between mysqli_connect and mysqli_pconnect?
Answer:
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.
Q #17) Which function is used in PHP to count the total number of rows returned by any query?
Answer:
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"); $count=mysqli_num_rows($result);
Q #18) How can you create a session in PHP?
Answer:
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
Q #19) What is the use of imagetypes() method?
Answer: 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"; }
Q #20) Which function you can use in PHP to open a file for reading or writing or for both?
Answer: 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
Q #21) What is the difference between include() and require()?
Answer: 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”;
Q #22) Which function is used in PHP to delete a file?
Answer:
unlink() function is used in PHP to delete any file.
Sample code:
unlink('filename');
Q #23) What is the use of strip_tags() method?
Answer: strip_tags() function is used to retrieve the string from a text by omitting HTML, XML and PHP tags. This function has one mandatory parameter and one optional parameter. The optional parameter is used to accept particular tags.
Sample code:
//Remove all tags from the text 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>");
Q #24) How can you send an HTTP header to the client in PHP?
Answer: The header() function is used to send raw HTTP header to a client before any output is sent.
Sample code:
header('Location: http://www.your_domain/');
Q #25) Which functions are used to count the total number of array elements in PHP?
Answer: count() and sizeof() functions can be used to count the total number of array elements in PHP.
Sample code:
$names=array(“Asa”,”Prinka”,”Abhijeet”); echo count($names); $marks=array(95,70,87); echo sizeof($marks);
Q #26) What is the difference between substr() and strstr()?
Answer:
substr() function returns a part of the string based on the starting point and length. Length parameter is optional for this function and if it is omitted then the remaining part of the string from the starting point will be returned.
strstr() function searches the first occurrence of a string inside another string. The third parameter of this function is optional and it is used to retrieve the part of the string that appears before the first occurrence of the searching 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
Q #27) How can you upload a file using PHP?
Answer: To upload a file by using PHP, you have to do the following tasks.
(i) Enable file_uploads directive
Open php.ini file and find out the file_uploads directive and make it on.
file_uploads = On
(ii) Create an HTML form using enctype attribute and file element for uploading the file.
<form action="upload.php" method="post" enctype="multipart/form-data"> <input type="file" name="upd" id="upd"> <input type="submit" value="Upload" name="upload"> </form>
(iii) Write a PHP script to upload 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."; }
Q #28) How can you declare a constant variable in PHP?
Answer: define() function is used to declare a constant variable in PHP. Constant variable declares without the $ symbol.
Sample code:
define("PI",3.14);
Q #29) Which function is used in PHP to search a particular value in an array?
Answer: in_array() function is used to search a particular value 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"; }
Q #30) What is the use of the $_REQUEST variable?
Answer: The $_REQUEST variable is used to read the data from the submitted HTML form.
Sample code:
Here, the $_REQUEST variable is used to read the submitted form field with the name ‘username’. If the form is submitted without any value, then it will print as “Name is empty”, otherwise it will print the submitted value.
<?php if (isset($_POST['submit'])) { // collect value of input field $name = $_REQUEST['username']; if (empty($name)) { echo "Name is empty"; } else { echo $name; } } else { ?> <form method="post" action="#"> Name: <input type="text" name="username"> <input type="submit" name="submit"> </form> <?php } ?>
Q #31) What is the difference between for and Foreach loop in PHP?
Answer: For loop is mainly used for iterating a pre-defined number of times and Foreach loop is used for reading array elements or MySQL result set where the number of iteration can be unknown.
Sample code:
//Loop will iterate for 5 times for ($n = 0; $n <= 5; $n++) { echo "The number is: $n <br>"; }
Sample code:
//Loop will iterate based on array elements $parts = array("HDD", "Monitor", "Mouse", "Keyboard"); foreach ($parts as $value) { echo "$value <br>"; }
Q #32) How long does a PHP session last for?
Answer: By default, session data will last for 24 minutes or 1440 seconds in PHP. But if you want, you can change the duration by modifying the value of gc_maxlifetime directive in php.ini file. To set the session time for 30 minutes, open php.ini file and set the value of gc_maxlifetime directive as follows,
gc_maxlifetime = 1800
Q #33) What is the difference between “= =” and “= = =” operators.
Answer: “= = =” is called strictly equivalent operator that is used to check the equivalency of two values by comparing both data types and values.
Sample code:
10 and “10” are equal by values but are not equal by data type. One is a string and one is a number. So, if the condition will be false and print “n is not equal to 10”.
$n = 10; if ($n === "10") echo "n is equal to 10"; else echo "n is not equal to 10"; //This will print
Q #34) Which operator is used to combine string values in PHP?
Answer: Two or more string values can be combined by using ‘.’ operator.
Sample code:
$val1 = "Software "; $val2 = "Testing"; echo $val1.$val2; // The output is “Software Testing”
Q #35) What is PEAR?
Answer: The full form of PEAR is “PHP Extension and Application Repository”.
Anyone can download reusable PHP components by using this framework at a free of cost. It contains different types of packages from different developers.
Website: PEAR
Q #36) What type of errors can be occurred in PHP?
Answer: Different type of errors can occur in PHP.
Some major error types are mentioned below:
- Fatal Errors– The execution of the script stops when this error occurs.
Sample code:
In the following script, f1() function is declared but f2() function is called which is not declared. The execution of the script will stop when f2() function will call. So, “Testing Fatal Error” will not be printed.
function f1() { echo "function 1"; } f2(); echo “Testing Fatal Error”;
- Parse Errors– This type of error occurs when the coder uses a wrong syntax in the script.
Sample code:
Here, semicolon(;) is missing at the end of the first echo statement.
echo "This is a testing script<br/>" echo "error";
- Warning Errors- This type of error does not stop the execution of a script. It continues the script even after displaying the error.
Sample code:
In the following script, if the test.txt file does not exist in the current location then a warning message will display to show the error and print “Opening File” text by continuing the execution.
$handler = fopen("test.txt","r"); echo "Opening File";
- Notice Errors- This type of error shows a minor error of the script and continues the execution after displaying the error.
Here, the variable, $a is defined but $b is not defined. So, a notice of the undefined variable will display for “echo $b” statement and print “Checking notice error” by continuing the script.
Sample code:
$a = 100; echo $b; echo "Checking notice error";
Q #37) Does PHP support multiple inheritances?
Answer: PHP does not support multiple inheritances. To implement the features of multiple inheritances, the interface is used in PHP.
Sample code:
Here, two interfaces, Isbn and Type are declared and implemented in a class, book details to add the feature of multiple inheritances in PHP.
interface Isbn { public function setISBN($isbn); } interface Type{ public function setType($type); } class bookDetails implements Isbn, Type { private $isbn; private $type; public function setISBN($isbn) { $this -> isbn = $isbn; } public function setType($type) { $this -> type = $type; } }
Q #38) What are the differences between session and cookie?
Answer: The session is a global variable that is used in the server to store the session data. When a new session creates the cookie with the session id is stored on the visitor’s computer. The session variable can store more data than the cookie variable.
Session data are stored in a $_SESSION array and Cookie data are stored in a $_COOKIE array. Session values are removed automatically when the visitor closes the browser and cookie values are not removed automatically.
Also read =>> Laravel Session tutorial
Q #39) What is the use of mysqli_real_escape_string() function?
Answer: mysqli_real_escape_string() function is used to escape special characters from the string for using a SQL statement
Sample code:
$DBconnection=mysqli_connect("localhost","username","password","dbname"); $productName = mysqli_real_escape_string($con, $_POST['proname']); $ProductType = mysqli_real_escape_string($con, $_POST['protype']);
Q #40) Which functions are used to remove whitespaces from the string?
Answer: There are three functions in PHP to remove the whitespaces from the string.
- trim() – It removes whitespaces from the left and right side of the string.
- ltrim() – It removes whitespaces from the left side of the string.
- rtrim() – It removes whitespaces from the right side of the string.
Sample code:
$str = " Tutorials for your help"; $val1 = trim($str); $val2 = ltrim($str); $val3 = rtrim($str);
Q #41) What is a persistence cookie?
Answer: A cookie file that is stored permanently in the browser is called a persistence cookie. It is not secure and is mainly used for tracking a visitor for long times.
This type of cookie can be declared as follows,
setccookie ("cookie_name", "cookie_value", strtotime("+2 years");
Q #42) How can a cross-site scripting attack be prevented by PHP?
Answer: Htmlentities() function of PHP can be used for preventing cross-site scripting attacks.
Q #43) Which PHP global variable is used for uploading a file?
Answer: $_FILE[] array contains all the information of an uploaded file.
The use of various indexes of this array is mentioned below:
- $_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.
Q #44) What is meant by public, private, protected, static and final scopes?
Answer:
- 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.
Q #45) How can image properties be retrieved in PHP?
Answer:
- 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.
Q #46) What is the difference between abstract class and interface?
Answer:
- 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 multiple abstract classes.
- Common behavior can be implemented in the abstract class but not an interface.
Q #47) What is garbage collection?
Answer: It is an automated feature of PHP.
When it runs, it removes all session data which are not accessed for a long time. It runs on /tmp directory which is the default session directory.
PHP directives which are used for garbage collection include:
- session.gc_maxlifetime (default value, 1440)
- session.gc_probability (default value, 1)
- session.gc_divisor (default value, 100)
Q #48) Which library is used in PHP to do various types of Image work?
Answer: Using the GD library, various types of image work can be done in PHP. Image work includes rotating images, cropping an image, creating image thumbnail, etc.
Q #49) What is URL rewriting?
Answer: Appending the session ID in every local URL of the requested page for keeping the session information is called URL rewriting.
The disadvantages of these methods are, it doesn’t allow persistence between the sessions and, the user can easily copy and paste the URL and send it to another user.
Q #50) What is PDO?
Answer: The full form of PDO is PHP Data Objects.
It is a lightweight PHP extension that uses a consistence interface for accessing the database. Using PDO, a developer can easily switch from one database server to the other. But it does not support all the advanced features of the new MySQL server.
Suggested reading =>> Laravel Interview Questions
Conclusion
I hope, this article will increase your confidence level to face any PHP interview. Feel free to contact us and suggest missing PHP Interview questions that you face in an interview.
Wish you all success for your interview!!