Php Interview Questions and Answers With Examples

Php interviw Questions Answers

1. How many ways to comment in php code?

There are multiple ways to comment in PHP. The main use of commentting is to understand in future, what you did. Some times it is difficult to understand code which we have done many times ago, but if we commenting correctly then it will saves our time and any other developer time who trying to understand the code in future.

Types of commenting in PHP

a. Single line commentting

<!DOCTYPE html>
<html>
 <body>
  <?php
   // comment with double slash 
   # commnt with hash symbol
  ?>
 </body>
</html>

b. Multiple line commentting

<!DOCTYPE html>
<html>
 <body>
  <?php
   /*
   For multi line comments
   */
  ?>
 </body>
</html>

2. How many types of loop in php?

In PHP there are 4 types of loops: for loop,while loop, do while loop and foreach loop which are used to execute blocks, posts one by one until a certain condition becomes true.

  • for: In for loop if the value is TRUE it will continuesly, if the value will FALSE then the loop will ends.
  • while: It will execute when a certain condition is TRUE.
  • foreach: It works with array in loop.
  • do while: IFirst it will check the condition and then execute on a specific condition.

Types of loops in PHP with example

a. For loop

<?php
  for ($e = 0; $e <= 3; $e++) {
    echo " Output is: ".$e."<br>";
  }
?>

b. While loop

<?php
  $e = 10;
  while($e <= 13) {
    echo "Result is: ".$e."<br>";
    $e++;
  } 
?>

c. Do While loop

<?php
  $e = 10;
  do {
    echo "Result is: ".$e."<br>";
    $e++;
  } while ($e <= 13);
?>

d. Foreach loop

<?php
   $eArray = array('apple','banana','guava');
  foreach($eArray as $row){
    echo "Result is: ".$row."<br>";
  }
?>

3. How to create database connection with OOPS and use it?

In latest PHP mysqli function is used to make a connection with mysql database and function mysqli_query() is used to execute a query like select, insert, update and delete from database.

First I will create a db connection file functions.php, where my host name is `localhost`, user name is `root`, password blank('') and database name is `dbname`.

functions.php

<?php
  function dbConnection(){
    return new mysqli('localhost', 'root', '', 'dbname');
  }
?>

After that i will create a new file insert.php, where i will execute a query to insert a record in `student` table using dbConnection() function which i have created above for make a database connection.

insert.php

<?php
  include 'functions.php';
  $query = "insert into student (name,email) values('ecode','emaltest@gmail.com')";
  $result = mysqli_query(dbConnection(),$query); 
?>

4. How to use session with php?

Session variables are stores on server. $_SESSION global variable is used to set session in php. We have to use function session_start() to use session in php. We can get session variables on all pages after set it on a single page, no need to set it on all pages. With session we can hold single user information in application in multiple pages.

session_unset() and session_destroy() functions are used to destroy the session global variables. In php we use session for user auth for application pages. (login, auth pages, logout)

Set session variable

<?php
  session_start();
  $_SESSION["session_key"] = "Key Value";
?>

Get session variable

<?php
  session_start();
  echo "Value of session variable is: :".$_SESSION["session_key"];
?>

Remove all session variables

<?php
  session_start();
  session_unset();
?>

Destroy session

<?php
  session_start();
  session_destroy();
?>

5. How many types of array in php?

In php an array is used to stored multiples values with in a single variable using keys. If you have list of items then you can stored them in a single veriable using index and get any specified value by key name.In php we can create our array variable using array() function.

There are three types of array in php: indexed, multipledimensional and associative.

Indexed array

Index array start form 0 and all elements in array are represent by a index key.

Indexed array

<?php
  $myArray = array('mango', 'grape', 'guava');
  echo $myArray[0]; // it will print mango
  echo $myArray[1]; // it will print grape
  echo $myArray[2]; // it will print guava
?>

Associative array

In associative array we can use custom keys name of array elements. Every key name in array must be unique otherwise array element value will overright.

Associative array

<?php
  $myArray = array('fruit'=>'mango', 'vegetable'=>'potato', 'gadget'=>'mobile');
  echo $myArray['fruit']; // it will print mango
  echo $myArray['potato']; // it will print potato
  echo $myArray['gadget']; // it will print mobile
?>

Multipledimensional array

In multidimensional array an array variable which consists of more than one array. Two-dimensional array and three-dimensional array are types of multidimensional array.

Multipledimensional array

<?php
  $myArray = array (
    array('mango', 'grape', 'guava'),
    array('banana', 'apple', 'pineapple'),
    array('avacado', 'cherry', 'orange')
  );
  echo $myArray[0][0]."--".$myArray[0][1]."--".$myArray[0][2].".<br>"; // it will print values of 1st array 
  echo $myArray[1][0]."--".$myArray[1][1]."--".$myArray[1][2].".<br>"; // it will print values of 2nd array 
  echo $myArray[2][0]."--".$myArray[2][1]."--".$myArray[2][2].".<br>"; // it will print values of 3rd array 
?>

Destroy session

<?php
  session_start();
  session_destroy();
?>

6. Select, Insert, Update, Delete with mysql in php

In php mysqli_query() function is used to execute an SQL query in MySql. Mainly it can be used to storing, retriving, manipulating the data and their are four types of queries: select, insert, update and delete.

Before execute queries, we have to establish a database connection.

<?php
  $conn = new mysqli('localhost', 'root', '', 'dbname');
?>

Select query

Select query is used to retriving data from database table. In below example, we will fetch data from students table.

Select

<?php
  $query = "SELECT * FROM students";
  $rows = mysqli_query($conn, $query);
  if ($rows->num_rows > 0) {
    while($row = $rows->fetch_assoc()) {
      echo "Student name: ". $row['name']."<br>";
    }
  }
?>

Insert query

Insert query is used to add news rows in database table. In below example, i will insert new records in students table.

Insert

<?php
  //Insert single record
  $query = "INSERT INTO students (name, roll_no) VALUES('teja', '101')";
  //Insert multiple records
  $query = "INSERT INTO students (name, roll_no)  
        VALUES('hema', '102'), ('shabo', '103')"; 
  mysqli_query($conn, $query);
?>

Update query

Update query is used to update an record in database table. In below example, i will update name of the student where student id is 32 from students table.

Update

<?php
  $query = "UPDATE students SET name='jhon' WHERE id=32";
  mysqli_query($conn, $query);
?>

Delete query

Delete query is used to delete an record in database table. In below example, i will delete a student record where student id is 32 from students table.

Delete

<?php
  $query = "DELETE FROM students WHERE id=32";
  mysqli_query($conn, $query);
?>

7. Difference between GET and POST method in php

GET and POST methods are HTTP methods, which are used to send HTTP requests to server from client side. After that server return a reponse which contains status information.

GETPOST
Request remains in browser historyRequest do not remains in browser history
Request send in URLRequest send in HTTP headers
Restrictions in request length. send unlimited data sizeNo restrictions in request length
Not secureSecure than GET request
Request can be bookmarkedRequest can not be bookmarked

POST method

<?php
if(isset($_POST["submitbutton"])) {
  print_r($_POST);
  exit();
}
?>
<html>
  <body>
    <form action = "<?php $_PHP_SELF ?>" method = "POST">
      Name: <input type="text" name="name">
      Email: <input type="email" name="email">
      <input type = "submit" name="submitbutton">
    </form>
  </body>
</html>

GET method

<?php
if(isset($_GET["submitbutton"])) {
  print_r($_GET);
  exit();
}
?>
<html>
  <body>
    <form action = "<?php $_PHP_SELF ?>" method = "GET">
      Name: <input type="text" name="name">
      Email: <input type="email" name="email">
      <input type = "submit" name="submitbutton">
    </form>
  </body>
</html>

8. Commonly array functions used in php

Array functions are used to save our time while coding. These are inbuilt functions of php and her i'm going to explain them with some examples.

array_push : This function is used to insert an element after the end the end of an array.

array_push

<?php
  $myArray = array("potato","avacado");
  array_push($myArray,"tomato");
  print_r($myArray);
?>

array_pop : This function is used to delete last element from an array.

array_pop

<?php
  $myArray = array("potato","avacado");
  array_pop($myArray);
  print_r($myArray);
?>

array_keys : This function returns keys of array all elements of an array.

array_keys

<?php
  $myArray = array("vegetable"=>"potato","fruit"=>"avacado");
  $arrayKeys = array_keys($myArray);
  print_r($arrayKeys);
?>

array_diff : This function returns difference between two array OR returns unique values from two array.

array_diff

<?php
  $firstArray = array("0"=>"potato","1"=>"avacado","2"=>"mango");
  $secondArray = array("0"=>"potato","1"=>"avacado","2"=>"banana");
  $arrayDiff = array_diff($firstArray, $secondArray);
  print_r($arrayDiff);
?>

array_rand : This function is used to return (n) number of random elements from an array.

array_rand

<?php
  $myArray = array("potato","avacado","mango","banana","grapes");
  $rows=array_rand($myArray,4);
  echo $myArray[$rows[0]]."<br>";
  echo $myArray[$rows[1]]."<br>";
  echo $myArray[$rows[2]]."<br>";
  echo $myArray[$rows[3]];
?>

array_replace : It will replace value of first array by the value of second array.

array_replace

<?php
  $firstArray = array("0"=>"potato","1"=>"avacado","2"=>"mango");
  $secondArray = array("0"=>"potato","1"=>"avacado","2"=>"banana");
  $arrayRep = array_replace($firstArray, $secondArray);
  print_r($arrayRep);
?>

array_reverse : This function returns same array but in reverse order.

array_reverse

<?php
  $myArray = array("vegetable"=>"potato","fruit"=>"avacado");
  $arrayRev = array_reverse($myArray);
  print_r($arrayRev);
?>

arsort : This function is used to sort an array according to the values in descending order.

arsort

<?php
  $myArray = array("teja"=>"45","hema"=>"15","shabo"=>"43");
  $arraySort = arsort($myArray);
  print_r($arraySort);
?>

asort : This function is used to sort an array according to the values in ascending order.

asort

<?php
  $myArray = array("teja"=>"45","hema"=>"15","shabo"=>"43");
  $arraySort = asort($myArray);
  print_r($arraySort);
?>

krsort : This function is used to sort an array according to the keys in descending order.

krsort

<?php
  $myArray = array("teja"=>"45","hema"=>"15","shabo"=>"43");
  $arraySort = krsort($myArray);
  print_r($arraySort);
?>

ksort : This function is used to sort an array according to the keys in ascending order.

ksort

<?php
  $myArray = array("teja"=>"45","hema"=>"15","shabo"=>"43");
  $arraySort = ksort($myArray);
  print_r($arraySort);
?>

sort : This function is used to sort an array in ascending order by alphabets.

sort

<?php
  $myArray = array("teja", "hema", "shabo");
  $arraySort = sort($myArray);
  print_r($arraySort);
?>

array_search : This function is used to search value in array.

array_search

<?php
  $myArray = array("4"=>"teja", "8"=>"hema", "9"=>"shabo");
  echo array_search("hema",$myArray);
?>

count : This function returns length of an array.

count

<?php
  $myArray = array("teja"=>"45","hema"=>"15","shabo"=>"43");
  echo count($myArray);
?>

array_merge : It will merge two arrays and returns result in a single array.

array_merge

<?php
  $firstArray = array("0"=>"potato","1"=>"avacado","2"=>"mango");
  $secondArray = array("0"=>"potato","1"=>"avacado","2"=>"banana");
  $arrayRep = array_merge($firstArray, $secondArray);
  print_r($arrayRep);
?>

9. How to create and get an cookie in php?

A cookie is used to store some information in the browser from the server for identifies the user. Facebook and other social platforms use cookies to identifies user. We can create and get cookie using php

Set a cookie : setcookie function is used to create an cookie with three parametres cookie key, cookie values and time.

setcookie()

<?php
  $cookieKey = "userId";
  $cookieVal = "174673";
  //604800 means 7 days
  setcookie($cookieKey, $cookieVal, time() + (604800 * 30), "/");
?>

Get a cookie : you can get all the cookies by global variable $_COOKIE. Now we get cookie value by key.

$_COOKIE

<?php
  if(isset($_COOKIE["userId"])) {
    echo "Name of your cookie is: ".$_COOKIE['userId'];
  } else {
    echo "Cookie not exist";
  }
?>

10. Difference between echo and print in php?

A cookie is used to store some information in the browser from the server for identifies the user. Facebook and other social platforms use cookies to identifies user. We can create and get cookie using php

Set a cookie : setcookie function is used to create an cookie with three parametres cookie key, cookie values and time.

setcookie()

<?php
  $cookieKey = "userId";
  $cookieVal = "174673";
  //604800 means 7 days
  setcookie($cookieKey, $cookieVal, time() + (604800 * 30), "/");
?>

11. Php CURL POST request

CURL is an php extension, which is used to GET and POST data from one server to another. It send HTTP request and get response status. In CURL we will send some peremetrs on a URL and get response with curl_exec() function.

Basic functions of CURL:

  • curl_init(): first initialize CURL at top
  • curl_setopt(): it will encode data
  • curl_exec(): it will execute and get response
  • curl_close(): request close

CURL with POST request

<?php
  //post fields
  $postFields = [
    'key_1' => 'value 1',
    'key_2' => 'value 2',
    'key_3' => 'value 3',
    'key_4' => 'value'4'
  ];
  $url = 'url here, where you want to post request';
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_POSTFIELDS, $postFields);
  //response will be in json format
  $response = curl_exec($ch);
  curl_close($ch);
?>

CURL with GET request

<?php
  $url = 'url here, where you want to post request';
  $ch = curl_init($url);
  curl_setopt($ch, CURLOPT_URL, $url);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  //response will be in json format
  $response = curl_exec($ch);
  curl_close($ch);
?>

12. Swap two numbers without using third variable

Here I will let you know how you can interchange values of two variable without using third variable. In below example their are two variables $s = 13 and $r = 33.

swap two numbers without using third variable

<?php
  $first = 13;
  $second = 33; 
  $first = $first + $second;  
  $second = $first - $second;  
  $first = $first - $second;  
  echo "After swap value of first:". $first ."</br>";  
  echo "After swap value of second:". $second ."</br>"; 
?>

We can also do swap using third variable.

swap two numbers using third variable

<?php
  $first = 13;
  $second = 33; 
  $third = $first;  
  $first = $second;  
  $second = $third;   
  echo "After swap value of first:". $first ."</br>";  
  echo "After swap value of second:". $second ."</br>"; 
?>

13. Difference between include and require

Sometimes, there is any section, element in our website which present many times on different pages, So it will takes lot of time to rewrite element again and again on different pages, that makes our code complex. To fix this problem we can create element template and call that template on multiple pages without rewrite code again and again. There are two ways to include template or file in different pages.

  • include
  • require

include and require both are same and identical to each other, both are used to include the files, only failure results are different.

includerequire
If file not exist it returns warningIf file not exist it returns error
Execution continues, if something went wrongStop execution, if something went wrong
Synatx: include("template.php");Syntax: require("template.php");

14. OOP`s with php

OOP full form is Object-Oriented Programming. OOP helps to make complex, reusable web applications. OOP creating objects which contains functions and information.

Object-Oriented Programming features:

  • Code reusability
  • Easier, faster and good for bulding complex applications
  • With OOP Code can be easily modifiable
  • In OOP One task can be performed in many ways
  • It provides clear structure for programming
  • Implements real life scenario
  • Bind functions and information in single unit

Object-Oriented Programming concepts:

Class : Class is collection of objects, a data type which defined by developer. Data type includes functions and information. You can think of a class as a template for making many instances of the same kind (or class) of object.

Object : It is an instabce which defined by class. We can create one class and defined multiples objects in it, every object is an instance of the main class.

Constructor : It will execute automatically when an object formation from a class

Destructor : Destructor is inverse of destructor and execute when an object is deleted.

Member Variable : Member Variable are that variables whcih defined inside a class. We can not used these variables outside of the class. Member variable can be accessed using member functions. Member variables are the attributes of object.

Member function : Member function are defined inside a class, which used to access data of the object.

Inheritance : Where class is derived from another class and that new child class will inherit all features, variables and member functions of parent class.

Parent class : Parent class is called base class or super class which inherited from by another class.

Child Class : Child class is called subclass or derived which inherits from another class.

Polymorphism : In polymorphism same function will used with different numbers of peremetre for different tasks.

Function Overloading : In function overloading function name is same but arguments are different which perform different tasks.

Function Overriding : In function overriding function name and function arguments are same of parent class as well as child class. Child class replace the method of parent class, function overriding is used to change the behaviour of parent class.

Data Abstraction : When implementation details are hidden on representation of data is known data abstraction.

Encapsulation : When we encapsulate member functions and data together to form an object.

15. How to use AJAX with php

Main purpose of AJAX is to perform database operations, without refreshing the browser. AJAX stands for Asynchronous JavaScript and XML, which will load the data in background. We will use ajax() method to use AJAX with php in jQuery.

In below example, i will insert a record in students table using ajax in php. I have create two files: index.php and post.php

index.php

<form id="foo">
  <label for="name">Name</label>
  <input id="name" name="name" type="text" value="" />
  <label for="rollno">Roll No</label>
  <input id="rollno" name="rollno" type="number" value="" />
  <label for="email">Email</label>
  <input id="email" name="email" type="email" value="" />
  <input type="submit" id="submitform" value="Send" />
</form>
<script>
$(document).ready(function() {
  $("$submitform").click(function(e) {
	e.preventDefault();
	var userName = $("#name").val();
	var userEmail = $("#email").val();
	var userRollno = $("#rollno").val();
    $.ajax({
      type: 'POST',
      data: {
        name: userName,
        rollno: userRollno,
        email: userEmail
      },
	  url:'/post.php',
      success: function(test){
		alert('Record inserted successfully in students tables');
      }
    });
  });
});
</script>

post.php

<?php
  $connection = mysqli('localhost', 'root', '', 'dbname');
  $query = "insert into students (name, rollno, email) values('".$_POST['name']."','".$_POST['rollno']."','".$_POST['email']."')";
  $result = mysqli_query($connection,$query); 
?>

16. Difference between in_array and array_search

in_array : in_array() function is used to check wheather a value exist in array on not.

array_search : array_search() return key of the value, if value will not found it return nothing.

in_array()

<?php
  $myArray = array("potato","avacado");
  if (in_array("avacado", $myArray)){
    echo "value exist in array";
  }
  else{
    echo "value not exist";
  }
?>

array_search()

<?php
  $myArray = array("s"=>"potato","r"=>"avacado");
  echo array_search("avacado", $myArray);
  //it will return key `r`
?>

17. Upload a file using php

To upload a file using php first we have to add an attribute `enctype="multipart/form-data"` to our form tag. multipart/form-data include the file of form in request data. Global variable $_FILES is used to get data of input file or upload fields via HTTP post method. Use below code to upload n image using php

<?php
  if(isset($_POST['submitform'])){
    if (isset ($_FILES['file'])) {
      $destinationPath = 'images/' . basename($_FILES['file']['name']);
      if (move_uploaded_file($_FILES['file']['tmp_name'], $destinationPath)) {
        echo "File saved in images folder";
      } 
	  else {
        echo "Something went wrong";
      }
    }
  }
?>
<form id="foo" action="" method="post" enctype="multipart/form-data">
  <label for="file">File</label>
  <input id="file" name="file" type="file" value="" />
  <input type="submit" name="submitform" value="Send" />
</form>

18. Upload multiple files using php

To upload multiple using php first we have to add an attribute `enctype="multipart/form-data"` and with input file type use name with array.

<?php
  if(isset($_POST['submitform'])){
    if (isset ($_FILES['files'])) {
      
      foreach ($_FILES['files']['tmp_name'] as $key => $value) { 
		$destinationPath = 'images/' . basename($_FILES['file']['name']);
		if (move_uploaded_file($_FILES['file']['tmp_name'], $destinationPath)) {
			echo basename($_FILES['file']['name'].' file saved';
		}
		else{
			echo 'error while saving '.basename($_FILES['file']['name'];
	    }
      }
    }
  }
?>
<form id="foo" action="" method="post" enctype="multipart/form-data">
  <label for="file">File</label>
  <input id="file" name="files[]" multiple type="file" value="" />
  <input type="submit" name="submitform" value="Send" />
</form>

Hi, I'm Saurav, the developer behind usingphp. Donate to help me keep usingphp free and maintained.

Please let me know what your thoughts or comments are on this article. If you have any suggestion or found any mistake in this article then please let us know.

Latest Comments

Rohit Agnihotri
Rohit Agnihotri
22 Dec 2020

Great! Found php unique questions here.

Ruby
Ruby
22 Dec 2020

All questions are important for my interview. Please add some more questions with examples

Add your comment