PHP Interview Questions with Answers 2020

In this article, you will get the most important PHP interview questions with answers 2020. It will be helpful to qualify for the technical interview. All the PHP questions contain the best example with an explanation. So, these questions will increase your confidence level for the interview.

If you are a Web developer and your working technology is PHP. You will have to face the technical interview round. But you have no idea of PHP questions that will be asked by the interviewer. So, It’s a big problem for PHP developers.

Don’t worry, I’m also a full-stack developer and I have faced many interviews. In each interview, Interviewer asked me common questions that are necessary for developers. So, I have collected these PHP Interview Questions and Answers according to my working experience.

php interview questions and answers

 

Contents

Top PHP Technical Interview Questions and Answers

I have shared the top 70 PHP Interview Questions and Answers that can help you to raise your confidence in the technical interview round. Even you will definitely get a respected job in the web development field.

Read Also

JavaScript Interview Questions and Answers 2020

 

Now, I’m going to explain PHP interview Questions with answers and examples through the following steps.

Most Important PHP Interview Questions

All the PHP Interview questions of this category are given for beginners and experienced developers. Generally, interviewers ask these types of questions. Because they want to check the coding level of developers so that they should select him/her for the next round.

1. What is PHP?

PHP is the back-end scripting language that runs on the server.

We can use the PHP script to make dynamic web pages.

We can download free to use for the web project.

PHP is the short form of Hypertext Preprocessor

2. What is the old name of PHP?

Personal Home Page

3. What is the current version of PHP

The current version of PHP: 7.4.6

Click here to check  PHP current version –

4. What are the differences between echo & print?

PHP Echo 

  • echo can accept multiple statements separated by the comma.
  • It runs faster than print.
  • It doesn’t return any value.

PHP Print

  • print can accept only a single statement.
  • It runs slower than echo
  • It always returns 1

5. What are the 10 string functions?

  • strlen()
  • explode()
  • implode()
  • str_rev()
  • str_word_count()
  • trim()
  • str_replace()
  • md5()
  • strtolower()
  • strtoupper()

Read an explanation of the above functions

6. How many types of the array?

The array is divided into three categories

  • Indexed Array
  • Associative Array
  • Multi-dimensional Array

Read an explanation of the above arrays

7. What are the 10 array functions?

  • count()
  • array_combine()
  • array_merge()
  • array_push()
  • array_pop()
  • array_revers()
  • array_sum()
  • array_product()
  • ksort()
  • krsort()

Read an explanation of the above functions

8. What is the difference between include() & require?

PHP include()

When We pass an unknown file to the include() function to use into another file, It will generate a warning error and will continue the execution of the next script.

Suppose that, you have included a file into another page using include() function and that file does not exist in your project folder. then you will get a warning error and will continue the execution of the next script.

PHP require()

When We pass an unknown file to the require() function to use into another file, It will generate a fatal error and stop the execution of the next script.

Suppose that, you have included a file into another page using require() function and that file does not exist in your project folder. then you will get a fatal error and will stop the execution of the next script

9. What is the difference between include & include_once?

We can use include() multiple times in a file to include files.

We can use include_once() only one time in a file to include files

10. What are the differences between post & get?

post Method

  • When we send data using post, it will not display in the browser URL bar
  • In the case of post, We can send an unlimited amount of data to the server.
  • post data is always secured
  • We can’t bookmark post data  to the browser
  • post data will not save in browser history

get Method

  • When we send data using get, it will display in the browser URL bar
  • In the case of get , We can send a limited amount of data to the server.
  • get data is less secured
  • We can bookmark get data to the browser
  • get data will not save in browser history

11. What are the superglobal variables?

  • $_GET['variableName']
  • $_POST['variableName']
  • $_GET['variableName']
  • $_REQUEST['variableName']
  • $_FILES['variableName']
  • $_SESSION['variableName']
  • $_COOKIE['variableName']
  • $_SERVER['variableName']

12. What is the difference between session & cookies?

Session

  • The session is stored in the server as a temporary variable.
  • It has no restriction on data, it can store an unlimited amount of data
  • It will be destroyed after closing the browser
  • The session is more secure than cookies

Cookies

  • Cookies are stored in the browser as a text file.
  • It has a restriction on data, it can store only a limited amount of data.
  • It will not be destroyed after closing the browser.
  • Cookies are less secure than the session.

13. What is difference between == and ===?

double equal ==

In the case of double equal==, comparison variables must have the same values to return true.

Suppose that, when we compare two variables using double equal==, it will return true. if the values of both variables are equal.

$a=20;   // integer type
$b="30"; // string type
if($a==$b)
{
 echo "I am true";
}
else
{
echo "I am False";
}

Triple equal===

In the case of triple equal ===, comparison variables must have the same values as well as the same data type to return true.

Suppose that when we compare two variables using triple equal ===. it will return true. if the values and datatype of both variables are equal

$a=20;   // integer type
$b="30"; // string type
if($a===$b)
{
 echo "I am true";
}
else
{
echo "I am False";
}

14. What is the difference between for loop and foreach loop?

for loop

  • It has a condition to execute at the specified times.
  • It can be used for an indexed array.

Example-

Suppose that, We have to print numbers 1 to 10, then we have to use for loop. because we know that loop will run 10 times

for($i=1;$i<=10;$i++)
{
echo $i." ";
}

We can use for loop for indexed array because we can find a number of times to execute it using count() method.

$arr=["noor","sunil","Amit","Anil"];
for($i=0;$i<count($arr); $i++)
{
  echo $arr[$i]." ";
}

foreach Loop

  • It has no condition to execute at specific times.
  • It can be used for an indexed array and associative array.

Example –

Suppose that, We have to print numbers 1 to 10, then we can’t use foreach loop. because it has no condition to declare a number of times

$arr=["noor","sunil","Amit","Anil"];
foreach($arr as $val)
{
  echo $val." ";
}

We can use foreach for indexed array and associative array because we need not declare the condition.

$arr=["name"=>"Noor","age"=>25,"city","Patna"];
foreach($arr as $val)
{
  echo $val." ";
}

15. What are the new features of PHP7?

  • Constant arrays using define()
  • Scalar type declarations
  • Return type declarations
  • Group use declaration
  • Null coalescing operator (??)
  • Spaceship operator
  • Anonymous classes
  • Closure::call method
  • Generator delegation

Read Explanation of above features

16. What is the difference between array_merge & array_combine?

array_merge()

We can merge one or more arrays into one array using array_merge() function.

Example -1

This example merges two index arrays

for indexed array
$arr1=array("Mohan","Radha","Amit");
$arr2=array("Sunil","Monika");
$mrg=array_merge($arr1,$arr2);
print_r($mrg);

Example – 2

This example merges two associative array

//for an indexed array
 $assoc1=array("a"=>Mohan","b"=>"Radha","c"=>"Amit"); 
 $assoc2=array("d"=>"Sunil","d"=>"Monika"); 
 $mrg2=array_merge($assoc1,$assoc2); 
 print_r($mrg2);

Example – 3

This example pass an associative array as a parameter to the array_merge()

//for an indexed array 
$assoc1=array("a"=>Mohan","b"=>"Radha","c"=>"Amit"); 
$mrg3=array_merge($assoc1); 
print_r($mrg3);

array_combine()

We can create an array with keys of one array and values of another array using array_combine() function.

Example -1

 
 $arr1=array("Mohan","Radha","Amit"); 
 $arr2=array("20","30","10"); 
 $mrg=array_merge($arr1,$arr2); 
 print_r($mrg);

17. What is the $this keyword?

$this is a representation of the current object of a class.

We must have to use a variable inside a method of a class using $this keyword.

Example

class Boy{
  
    public $profile="Developer";
    public function get_profile(){
       $result=$this->profile;
       return $result;
    }

}
$obj=new Boy();
echo $obj->get_profile(); // it returns Developer

18. What is the constructor?

The constructor is the special type of method of a class.

It will execute automatically after creating an object.

Normally, We have to access the custom method from an object of a class but we need not access the constructor method from an object.

Syntax –

 function__construct(){}

Example:

class Boy {
  public $name="Noor khan";
  public $age=25;

  function __construct() {
     echo $this->name;
  }
  function get_age() {
    echo $this->age;
  }
}

$obj = new Boy();
echo "<br>";
$obj->get_age();

19. What are the access modifiers?

There are three access modifiers such as

  • public –  If we declare properties or methods with the public modifier, we can access it from anywhere.
  • protected – If we declare properties or methods with the protected modifier, we can access it within its current class and into child class of that current class as well
  • private – If we declare properties or methods with the private modifier, we can access it only within its current class.
class Boy {
  public $name;
  protected $age;
  private $city;
}

$obj = new Boy();
$obj->name = 'Noor Khan';  
$obj->age = 25;   // It produces an error
$obj->city = 'Patna'; // It produces an error

20. What inheritance and explain different types of inheritance?

Inheritance

In the case of Inheritance, a class inherits all the properties & methods from another class with extends keyword.

  • Single Inheritance
  • Multiple Inheritance
  • Multilevel Inheritance
  • Hierarchical Inheritance
  • Hybrid Inheritance.

21. What is Single Inheritance

In this inheritance, We can create only one class from the other one class.

The created class will be child class and the other one class will be the parent class.

Child class may have its own properties & methods and it will also inherit all the properties & methods of the parent class.

Example

Suppose that, We have to create class Two from class One like the following derivation.

single inheritance - php interview questions

class One{
      
      public $a=50;
      public $b=20;
      public function addition(){
       $sum=$a+$b;
       echo $sum;
     }
}
class Two extends One{
   
     public function subtraction(){
        $sub=$a-$b;
        echo $sub;
    }


}

22. What is Multiple Inheritance

In this inheritance, We can create a child class from more than one parent class.

PHP does not support multiple Inheritance.

Example

Suppose that, We will create class Three from class One & class Two as the following derivation

Multi-level Inheritancemultiple_inheritance - php interview questions

23. What is Multi-level Inheritance

In this inheritance, We can create a child class from a parent class and again another child class from the created child class.

Example –

Suppose that, We will create a child class two from parent class one and another child class three from created child class two as the following derivation.

Multilevel_inheritance - php interview questions

class One{ 
      public $a=50; 
      public $b=20; 
      public function addition(){
           $sum=$a+$b; 
           echo $sum; 
      } 
} 
class Two extends One{ 
      public function subtraction(){
          $sub=$a-$b; 
         echo $sub;
      } 
}
class Three extends Two{ 
      public function multiplication(){
          $mul=$a*$b; 
         echo $mul;
      } 
}

24. What is Hierarchical Inheritance

In this inheritance, We can create more than one child classes from a single parent class.

Suppose that, We will create child class Two and another child class Three from parent class One as the following derivation.

Hierarchical_inheritance

class One{ 
public $a=50; 
public $b=20; 
public function addition(){ 
  $sum=$a+$b;
  echo $sum;
} 
} 
class Two extends One{ 
 public function subtraction(){ 
     $sub=$a-$b;
     echo $sub; 
} 
} 
class Three extends one{ 
public function multiplication(){ 
$mul=$a*$b;
echo $mul;
} 
}

25. Hybrid Inheritance

In this inheritance, We can create multiple classes by the combination of Multi-level, multiple & Hierarchical inheritance.

hybrid-inheritance

26. What is the difference between abstract & interface?

In PHP language, use of abstract class & interface are approx  similar but  some following points are absolutely different from each other

Abstract Class

  • In abstract class, We need not declare every method as an abstract
  • We can define as well as declare methods in the abstract class
  • We can declare methods of an abstract class with the public or protected both modifiers
  • In abstract class, We can declare the constructor method.
  • We can declare data members in an abstract class.

Interface

  • In the interface, We have to declare every method as  an abstract
  • We can only define methods in the interface.
  • We can only declare methods of interface with the public modifier.
  • In the interface, W can’t declare the constructor method
  • We can’t declare data members in an interface

27. What is a trait?

The trait is similar to a class but we can’t create an object from trait.

We can only use traits inside one or more classes with the use keyword.

Generally, We can use the traits for the purpose of the multiple inheritances.

Example –

<?php
trait One {
    public function traitOne() {
        echo 'I am trait one';
    }
}

trait Two {
    public function traitTwo() {
        echo 'I am trait Two';
    }
}

class Three {
    use One, Two;
    public function myFun() {
        echo 'I am a class';
    }
}

$obj = new Tree();
$obj->traitOne();
$obj->traitTwo();
$obj->myFun();
?>

28. What is a namespace?

The namespace is just like a folder.

The namespace is used to manage classes or methods of the same name that remain in the same file.

We can’t declare more than one class or method with the same name into a single file as the following code.

// declared two classes with the same name
class Work{
    
     public function myTask(){
       echo "I am learning namespace";
     }
}
class Work{
    
     public function ypurTask(){
       echo "I am learning namespace";
     }
}
// declared two methods with same name
    public function myName(){
       echo "My Name is namespace";
     }
 public function myName(){
       echo "My Name is namespace";
     }

But We can declare the above code with the namespace as following code.

// declared two classes with the same name 
namespace abc{
class Work{ 
 public function myTask(){
    echo "I am namespace abc";
 } 
} 
}

namespace xyz{
class Work{ 
  public function ypurTask(){ 
    echo "I am  namespace xyz";
  }
 } 
}
// declared two methods with same name 
namespace ab{
function myName(){ 
   echo "My Name is namespace ab"; 
} 
}
namespace{
public function myName(){ 
  echo "My Name is namespace";
 }
$onj1=new abc\Work();
$obj1->myTask();  // output- I am  namespace abc

$obj2=new xyz\Work();
$obj2->yourTask(); // output- I am  namespace xyz

myname();  // output- My Name is namespace
ab\myname(); // output- My Name is namespace ab
}

The namespace has some following rule

  • We can’t declare namespaces of the same name in the single file.
  • We can’t write any PHP codes outside the namespace.

29. What is the self keyword in PHP

Self represents static properties & methods of the current class.

Suppose that we have declared a variable with static keyword into the class like public status $name=”codingStatus” and a method like public myName(){}. Now I want to access $name into  myName(){} function.then We can access like the following code

class Coding{
     public static $name="codingStatus";
     public function myName(){
       echo "My Name is ".self::name;
     }

}

30. What are the differences between self and this keyword?

self keyword

  • self is a representation of static properties & methods of a class.
  • It will access the properties or methods using scope resolution operator ::
  • It does not begin with any symbol.

this keyword

  • $this is a representation of the current object of a class.
  • It will access the properties or methods using the arrow operator ->
  • It always begins $ symbol

31. What is Type Hinting

Type Hinting is the concept of passing array & object type variables to the function by declaring their datatype.

// passing an array

function detail(array $data){
     perint_r($data);

}
$data=["Noor",24,"Patna"];
detail($data);

//passing an object
class Boy{
   function  __construct()
   {
     echo "I am Boy Type class";
   }
}
$onj=new Boy();
detail(Boy $obj);

32. Write the mail function?

$to="receiver@gmail.com"; // Write the email id of mail receiver
$subject="php interview questino"; // Write your mail title
$message="You have best otiopn to learn php interview questions"; // write your message
$headers.="From:sender@gmail.com"; // write sender name or email id
mail($to,$subject,$message,$headers);

33. What is the query string?

The query string is used to pass the value from a page to another page through its URL.

Syntax-

url?object=value&object=value

Example – 1

Create a single query string in the following url

<a href="my-url.php?name=noor">Click here</a>
<a href="my-url.php?id=3">Get id</a>

Get value in my-url.php file using the following script

<?php
$name= $_GET['name'];
$id= $_GET['id'];

?>

Example – 2

Create two query string in a single  URL

<a href="my-url.php?name=noor&id=3">Click here</a>

Get value my-url.php page

<?php $name= $_GET['name']; 
$id= $_GET['id']; ?>

 

34. What is the recursive function?

When a function calls itself within its own body to execute several times.it will be a recursive function.

Example –

function number ($num)
{
    if ($num <= 0) return "Negative integer is not allowed";
    if ($num > 9) return "Counting is completed";
    else return number ($num+1);
}

35. What is the difference between implode() & explode()?

explode() function

  • it is used to create an array by breaking a string.
  • separator argument of explode() is required.

Syntax –

explode('separator','string');

Example –

$expStr="I am explode() function";
$expArr=explode(' ',$expStr);
print_r($expArr);

implode() function

  • It is used to create a string by joining elements of an array
  • separator argument of implode() is optional.

Syntax –

implode('separator','string');

Example –

$impArr=array('I','am','implode()','function');
$impstr=implode('',$impArr);
echo $impstr

Basic PHP Interview Questions for Freshers

These are the collection of basic level questions answers for face to face interview round.

These questions are more necessary for fresher developers and Experienced developers can prepare as well.

1. What We can do in PHP

We can do the following things

  • Dynamic content of the web page.
  • Create, read, write, open, close and delete files on the server
  • Insert,edit,update,delete data in the table

2. Is PHP variable a Case Sensitive?

Yes, because $var and $VAR are different  from each other

3. What is difference between define() & constant()

define() is used to create a constant variable.

constant() is to display the value of a constant variable.

Example –

define("codingstatus","Free coding tutorias for IT developers");
echo constant("codingstatus");

4. What is the magic constant?

Magic constant is the predefined function.

It has the double underscore__at the beginning and ending

Its value depends on where it is used.

Example

__LINE__  It returns the current line of its declaration.

echo "It is line no ".__LINE__; // it returns- It is line no 1
echo "It is line no ".__LINE__; // it returns- It is line no 2
echo "It is line no ".__LINE__; // it returns- It is line no 3

5. What are the different type of magic constants

PHP provides the following different types of magic constants

__LINE__
__DIR__
__FILE__
__FUNCTION__
__METHOD__
__NAMESPACE__
__CLASS__
__TRAIT__

6. How to find the string length in PHP?

We can calculate string length using strlen()

Example –

$str="I am codingStatus";
echo strlen($str);

7. What is XSS?

XSS is the short form of cross-site-scripting.

It allows hackers to insert front-end script to the web pages

8. Can we use a double quote inside another double quote?

No, because PHP allows us to use double quote inside a single code

9. What is isset() function?

We can check the variable is set or not using isset().

If the variable is set. it will return true otherwise false

If it has a null value will return false.

var $var="codingStatus";
if(isset($var)){
   echo "variable is set";
}
else{
   echo "variable is not set";
}
// for nul value
var $nullvar=null;
if(isset($nullvar)){
   echo "variable is set";
}
else{
   echo "variable is not set";
}

10. What are the differences between while loop and the do-while loop?

While Loop

  • While loop checks the condition  at the beginning of the loop
  • If the condition of the while loop will be false then the loop will not run.
  • The end of the while loop is not terminated by a semicolon.

do-while loop

  • do-while loop checks the condition at the ending of the loop
  • If the condition of the do-while loop will be false then the loop will run at least once.
  • The end of the do-while loop is terminated by a semicolon

11. How to increase the maximum execution time limit in PHP?

We  have the following two options to increase the maximum execution time limit

first, We can change the value of  given max_execution_time=30 in php.ini file

Second, We can declare the following code at the top of the script

ini_set('max_execution_time', '180'); //180 seconds = 3 minutes
ini_set('max_execution_time', '0'); // for infinite time of execution

12. How to use PHP with javascript?

We can’t use PHP code to an external javascript file. because it has .js extension but you know that PHP script can only execute in the file that has .php extension.

But we can use within the inline and internal javascript file like the following a script

<script>
<?php $a=10;$b=20; ?>
document.write(<?php echo $a+$b;?>);
</script>

13. How to display an array in PHP?

We can display the array using print_r().

$arr=['Noor','Sunil','Ayush'];
print_r($arr);

14. What is the difference between session_destroy & session_unset?

session_destroy- it can destroy all the registered data of the session.

session_unset- All session variables will be free by declaring it.

15. What is class

Class is a container which contains properties and method.

syntax- class ClassName{}

class Boy{
    
    public $fname="Coding";
    public $lname="Status";
    public function fullName(){
         echo $fname." ".$lname;
    }
}

16. What is the object?

An object is the instance of a class that is used to access its properties or methods.

It is created from a class such as new ClassName()

class Boy{ 
  public $fname="Coding";
  public $lname="Status";
  public function fullName(){ 
  echo $fname." ".$lname;
 } 
}

$obj=new Boy();
$obj->fullName();

17. What is the final class?

final class does not allow to create own object but it can be inherited by child classes.

Example –

If we have declared a class with the final keyword, we can’t create an object from that class. but We can access its properties through its child class.

final class Maths(){
    public $a=20;
    public $b=30;
    public function sum(){
      echo $a+$b;
    }
}
class Cal extends Maths{
   public function mul(){
          $mult=$this->a*$this->b;
          echo $mult;
   }
}
$obj=new Cal();
$obj->sum();
$obj->mul();

18. What is the difference between $var and $$var

Name of $$var is $vat but Name of $var is var

$$var is the reference variable but $var is the normal variable.

$name="Coding";
$$name="Status";
echo $name;  // it returns Coding
echo $$name; // It returns Status
echo $Coding; // It returns Status

19. What is Regular Expression?

The regular expression is the combination of characters.

It provides the functionality to match the pattern with searching characters

20. What is oops?

Opps is the short form of the object-oriented programming system

It is not a programming language. It’s a concept to make powerful and secure the source code.

Advanced PHP Interview Questions for Experienced

This is the collection of the basic Advanced PHP Interview Questions with answers and examples. It is more necessary for experienced developers. But Beginner developers may prepare these types of questions.

1. Who is the founder of PHP?

Rasmus Lerdorf

2. what are the advantage of PHP?

  • PHP is light-weight and fast execution
  • PHP is free to use.
  • It can run on any operating system like Windows, UNIX, MAC
  • It can support  many databases like Oracle, MySQL, SQL Server
  • PHP can also support OOPS concept

3. In which language PHP was written

PHP Script was written in C & C++

4. Explain 10 string functions.

strlen() Function

It is used to calculate the length of a string
Example – 1

$strlen="I am a string";
echo strlen($strlen);

explode() Function

It creates an array from a string

$expStr="I am a string";
$expArr=explode('',$expStr);
print_r($expArr);

implode() Function

It creates a string from an array

$impArr=["I","am","an","array"];
$impStr=implode($impArr);
echo $impStr;

str_rev() Function

It can display a string in the opposite direction.

By default, a string seems from left to right. but str_rev  reverse it from right to left

$myStr="I am a string";
$strRev=str_rev($myStr);
echo $strRev;

str_word_count() Function

It is used to calculate the total number of words of a string.

$myStr="I am a string";
$words=str_word_count($myStr);
echo $words;

trim() Function

It removes the whitespaces from both sides of a string.

It can also remove custom characters from both sides of a string

$str = "Coding Status";
echo $str . "<br>";
echo trim($str,"Cus");

str_replace() Function

It is used to replace characters of the string.

$str="Coding Status";
echo str_replace("Coding","Noor",$str);

md5() Function

It is used to calculate the md5 hash of a string

$myStr="I am a string";
echo md5($myStr);

strtolower() Function

It is used to display a string into lowercase.

$myStr="I AM A STRING";
echo strtolower($mystr);

strtoupper() Function

It is used to display a string into uppercase

Example

$myStr="I am a string";
echo strtoupper($myStr);

5. Explain 10 array functions.

count() Function

It is used to calculate the total number of elements of an array

$arr=["I","am","a","string"];
echo count($arr);

array_combine() Function

It creates a new array using keys from the first array and values from the second array.

$arr1=array('Name','Age','City');
$arr2=array('Noor',25,'Patna');
$arrComb=array_combine($arr,$arr2);
print_r($arrComb);

array_merge() Function

It creates an array by merging elements of two arrays

$arr1=array('Name','Age','City'); 
$arr2=array('Noor',25,'Patna'); 
$arrComb=array_merge($arr,$arr2); 
print_r($arrComb)

array_push() Function

It is used to insert  one or more elements into an array

$arr=array("Amit","Sumit","Ravi");
$arrPush=array_push($arr,"Mohan","Radha");
print_r($arrPush);

array_pop() Function

It is used to remove the last element of an array

$arr=array("Amit","Sumit","Ravi"); 
$arrPop=array_pop($arr); 
print_r($arrPop);

array_revers() Function

It can reverse elements of an array.

$a=array("Amit","Sumit","Ravi");
print_r(array_reverse($a));

array_sum() Function

It is used to add elements of an array.

$arr=array(30,20,40);
$arrSum=arrar_sum($arr);
echo $arrSum

array_product() Function

It is used to multiply elements of an array

$arr=array(30,20,40);
$arrMult=array_product($arr); 
echo $arrMult;

ksort() Function

According to the key, It is used to convert an associative array in ascending order.

$arr=array("Amit"=>"35","Sunil"=>"24","Mohan"=>"18");
ksort($arr);

foreach($arr as $key=>$value)
   {
   echo "Name: " . $key . ",  -Age: " . $value;
   echo "<br>";
   }

krsort() Function

According to the key, It is used to convert an associative array in descending order.

$arr=array("Amit"=>"35","Sunil"=>"24","Mohan"=>"18"); 
krsort($arr); 
foreach($arr as $key=>$value) { 
 echo "Name: " . $key . ", -Age: " . $value; echo "<br>"; 
}

6. What are the differences between pre & post-increment?

pre-increment

First of all, It increases the value by one then returns then it will return the value.

In the case of pre-increment, a variable begins with a double plus sign like ++$x

$num = 100;  
echo ++$num;
echo "<br>";
echo $num;

post-increment

First of all, It returns then it will increase the value.

In the case of post-increment, a variable ends with a double plus sign like $x++

$num = 100;  
echo $num++;
echo "<br>";
echo $num;

7. What are the differences between pre & post decrement?

pre-decrement

First of all, It decreases the value by one then returns then it will return the value.

In the case of pre-decrement, a variable begins with a double plus sign like –$x

$num = 100;  
echo --$num;
echo "<br>";
echo $num;

post-decrement

First of all, It returns then it will decrease the value.

In the case of post-decrement, a variable ends with a double plus sign like $x–

$num = 100;  
echo $num--;
echo "<br>";
echo $num;

8. What is difference between <> and !==

Not equal <>

In the case of Not Equal, comparison variables must not have the same value to return true.

Suppose that we compare two variables using Not equal.it will return true, if values of both variables are not equal.

$a=20;   // integer type
$b="30"; // string type
if($a<>$b)
{
 echo "I am true";
}
else
{
echo "I am False";
}

Not identical !==

In the case of Not identical, comparison variables must not have the same value as well as the same data type to return true.

Suppose that we compare two variables using Not identical.it will return true, if values of both variables & datatype are not equal.

$a=20;   // integer type
$b="30"; // string type
if($a!==$b)
{
 echo "I am true";
}
else
{
echo "I am False";
}

9. What are PHP filter Extension and its function?

Filter Extension

It used to validate data & remove illegal characters from the data.

It has the following function that is mostly used to validate the data.

filter_var()

It  can validate the data and convert in the proper format

Example-1

Validation of an email

$email = "codingstatus@gmail.com";

$checkEmail = filter_var($email, FILTER_SANITIZE_EMAIL);

if (filter_var($checkEmail, FILTER_VALIDATE_EMAIL) === true) {
    echo(" valid email address");
} else {
    echo("invalid email address");
}

Example- 2

validation of a URL

$url = "https://www.codingstatus.com";

$checkURL = filter_var($url, FILTER_SANITIZE_URL);

if (filter_var($checkURL, FILTER_VALIDATE_URL) === true) {
    echo("valid URL");
} else {
    echo("Invalid URL");
}

Example-3

Validation of a string to remove HTML element

$str = "<h1>I am CodingStatus</h1>";
$removeHTML = filter_var($str, FILTER_SANITIZE_STRING);
echo $removeHTML;

10. Explain different New Features of PHP7

Constant arrays using define()

We can use define() to create a constant array

define("coding", [
    "PHP",
    "HTML",
    "Python"
]);
echo coding[0];

Scalar type declarations

We can pass arguments to the function with their data type

function bio(string $name,int $age)
{
  echo "My name is: ".$name;
  echo "<br>";
  echo "My age is: ".$age;
}

$name="Noor Khan";
$age=25;
bio($name,$age);

Return type declarations

We can declare the data type of a function to return declared type of value.

function sum($a,$b):int{
    return $a+$b;
}

echo sum(30,80);

Group use declarations

We can group one or more entities from a common namespace

namespace first{
   class A{}
   class B{}
   class C{}
   class D{}
}

namespace{
  
   first\A;
   first\B;
   first\C;
   first\D;
   or
// Group declarations
   first\{A,B,C,D};
   


}

Null coalescing operator (??)

We can check the value is exist or not null using Null coalescing operator.

Syntax $var= statement1 ?? statement2;

if $var has a value & not null,It will return statement1

echo $name = $_GET["name"] ?? "No value";

Spaceship operator

It is a combination of less than, equal to and greater than, operators.

It is used to compare two values  $var1 and $var2 as the following condition

  • if $var1 is less than $var2, it will return -1
  • When $var1 is equal to $var2, it will return 0
  • if $var1 greater than $var2,it will return 1

Example –

$var1 = 99;  
$var2 = 100;

echo ($var1 <=> $var2); // returns -1 because $var1 is less than $var2
echo "<br>";

$var1 = 99;  
$var2 = 99;

echo ($var1 <=> $var2); // returns 0 because values are equal
echo "<br>";

$var1 = 100;  
$var2 = 99;

echo ($var1 <=> $var2); // returns 1 because $var1 is greater than $var2

Anonymous classes

We can declare a class without its name that is known as Anonymous class.

$obj=new class(){
  
  function __construct(){
    
      echo "I am an anonymous class";
    }

};

Closure::call method

It is used to bind an object’s scope to a closure method.

Example –

 class A {
      private $name = "Noor Khan";
   }

   // PHP 7+ code, Define
   $value = function() {
      return $this->name;
   };

   print($value->call(new A)); // it returns Noor Khan

Generator delegation

It is a function that returns many required values using yield.

A function that contains yield, will be a generator function.

function print_number() {
    for ($i = 1; $i <= 5; $i++) {
       
        yield $i;
    }
}

$generator = print_number();
foreach ($generator as $value) {
    echo "$valuen";
}

11. What are the different types of errors?

Php has three types of errors as

  • Notice Error
  • Warning Error
  • Fatal Error

Notice Error

If We access a variable that is not declared. We will generate a notice error;

echo $num;

Warning Error

If We pass the wrong parameter to the function. We will get a warning error and all the script will  execute.

Suppose that We pass an unknown file to include(), we will get a warning error.

include(unknown-file.php);

Fetal Error

When we call a function that is not defined. We will get a fatal error and all the script will not execute.

demo();

suppose that We pass an unknown file to require().we will get a fatal error.

require('unkonwn-file.php');

12. What are the advantages of OOPS?

  • OOPS is a real-world programming concept
  • It can hide the information to keep secure the code.
  • It allows us to reuse the code.

13. What are the functions of regular expression?

There are five different functions of regular expression

  • preg_match()
  • preg_match_all()
  • preg_replace()
  • preg_split()
  • preg_grep()
  • preg_quote()

14. Explain different types of array

Indexed Array

It  has numeric index that begins from 0 to number of declared elements.

$arr1=array('Noor',25,Patna);
or
$arr2=['Noor',25,Patna];

Associative Array

An associative array  can have the custom index and its indexes & values are declared with an arrow symbol=>

You can create a custom index in an associative array and Custom index may be a number or string.

$arr=array("Name"=>"Noor","Age"=>25,"City"=>"Patna");
or
$arr1=["Name"=>"Noor","Age"=>25,"City"=>"Patna"];

Multi-dimensional Array

It is a nested array that contains one or more arrays.

$multiArr=array(
         
        array('25',30,40),
        array('Noor','Sunil','Ayush'),
        array('Patna','Delhi','Noida')

);

PHP Coding Questions for Interview

These types of PHP Interview Questions are coding based questions for the written test.

These questions more necessary for experienced developers and freshers can prepare as well

These questions will clear your coding concept and learn you to develop logic.

After preparing the javascript coding question, you will able to solve any level of questions.

Generally, interviewers will ask questions based on the concept of these listed questions in the written test. Therefore you must do practical of these questions again and again.

1. What is the data type of $x=34.2

$x=34.2;

echo gettype($x); // output- double

Suggestion

Dear Developers, I hope that All the given PHP interview questions and answers will be helpful to get the job in the web development field. If you have any queries related to this topic or another coding language, kindly, ask me without any hesitation through the comment box.

I will share more tutorials related to the coding field to solve your problem. Therefore you should continue to visit my site. Thank You…

 

Categories PHP

1 thought on “PHP Interview Questions with Answers 2020”

Leave a Comment