Top 50 PHP Interview Questions and Answers

These are the top 50 interview questions and answers that have been asked in most of the interviews.

Q.1 What is PHP?

  1. Answer: PHP is a server-side scripting language used mainly for creating web-based applications. However, we can also use it as a general-purpose programming language. It is an open-source language, which means we don’t have to pay anything to use it. It is freely available over the internet.

Q. 2. What is inheritance?

Answer: Inheritance is a feature of object-oriented programming in which a child class can access the properties and methods of its parent class. There are five types of inheritance – Single inheritance, multiple inheritance, multilevel inheritance, hierarchical inheritance, and hybrid inheritance. Out of these, PHP only supports single inheritance.

Example of Inheritance

<?php
    class ElectronicDevices{
        public function usesElectricity(){
            echo "This device uses electricity.";
        }
    }

    class Computer extends ElectronicDevices{
        public function usesCPU(){
            echo "This device has a CPU.";
	}
    }

    $obj = new Computer();
    $obj->usesElectricty();
    echo "<br />";
    $obj-usesCPU();
?>

Q. 3. What is the difference between echo and print?

Answer: echo and print both are used to display some values, however, there are some differences between the two.

  1. echo can print multiple values at a time while print cannot.
  2. print has a return value of 1 whereas echo does not have any return value.
  3. echo is faster than print.

Q. 4. What is the difference between empty() and isset() functions?

Answer: Both isset and empty are inbuilt functions of PHP, used to check if a variable has some value (other than null). If the variable does not exist, the isset() function will generate a warning. However, if are using the empty() function, it will not generate any warning if the variable does not exist.

Q. 5. What is the difference between a session and a cookie?

Answer: Both session and cookie are used to store some user data. However, there are some differences between the two.

 

Session Cookie
A session gets stored on the server. A cookie gets stored on the client’s browser.
A session is more secure than a cookie. Cookies are not secured
The superglobal $_SESSION is used to get all the session data stored. $_COOKIES is a superglobal which is used to retrieve the cookies stored.
To destroy a session we use an inbuilt function session_destroy. To set an expiry to the cookies we need to set a specific time
A session gets destroyed when the user either logs out from the application or closes the browser. Cookies get destroyed with a specific time set by the user.

Q. 6. Where is the session gets stored?

Answer: The session gets stored on the server. Whenever a new session starts, a unique session ID is generated. This session id gets stored in a directory named as ‘tmp’ on the server. It will be there until the session ends.

Q. 7. How many types of inheritance are there in PHP?

Answer: PHP only supports single inheritance. This means there should be only a parent class and a single-child class.

Q. 8. What is a constant in PHP?

Answer: A constant is an identifier for a value that cannot be changed during the script execution. Unlike a variable, a constant cannot be changed once defined.

To create a constant, we can use the define function.

For Example:

<?php
    define('WEEKDAYS', 'There are seven days in a week');
    echo WEEKDAYS;
?>

Output:

There are seven days in a week.

We cannot write the echo statement like – ‘echo weekdays’ in the above script. However, we can use the constant in a case-insensitive way by providing ‘true’ as the third argument in the define function.

<?php
    define('WEEKDAYS', 'There are seven days in a week', true);
    echo weekdays;
?>

Output:

There are seven days in a week.

Q. 9. What are static properties and static methods?

Answer: A static property is a property defined inside a class that would be the same for all objects. It does not need to create an object to access a static property. A static property can be declared by using the static keyword in PHP.

A static property can be accessed outside the class by using the class name followed by the scope resolution operator(::).

For example

<?php 
    class Boy{ 
        public static $gender = "Male"; 
        public function __construct(){ 
            //Code inside the constructor. 
        } 
        public function displayGender(){ 
            echo "The gender is " . self::$gender; 
        } 
    } 
    echo Boy::$gender; 
?>

Output:

Male

Inside the class, it can be accessed using the self keyword. It should be noted that a static property cannot be accessed using the ‘this’ keyword.

<?php
	
    class Boy{
        public static $gender = "Male";
		
        public function __construct(){
	    //Code inside the constructor.
	}
		
	public function displayGender(){
	    echo "The gender is " . self::$gender;
	}
    }
	
    $boyObj = new Boy();
    $boyObj->displayGender();
	
?>

Output:

The gender is Male

Q. 10. What are access specifiers?

Answers: The access specifiers or access modifiers decide the grant for using a specific method or property of a class.
These are three types of access specifiers in PHP-

  1. Public
  2. Private
  3. Protected
  4. Abstract
  5. Final

The first three specifiers can be applied to the class members(properties and methods), whereas the last two can only be applied to the classes.

  • Public: The public specifier states that the public property or public method can be used anywhere in your script. Even outside the class scope.
  • Private: When we define a property or method as private, it could only be accessed within that class.
  • Protected: This is similar to a private specifier. The private class members(properties and methods) can only be accessed within the class itself or it’s child class(subclass).
  • Abstract: This is used for classes in PHP. An abstract class is one which has at least one abstract method. An abstract method is one which is declared but not defined.
  • Final: A final class is one which cannot be further inherited by other classes.

Q. 11. Is it possible to define a class that could not be extended? If so, how?

Answer: Yes it is possible. This type of class is called a final class and it could not be extended further. A final class can be created by using the final keyword. If you try to extend a final class, you will get an error.

<?php
    final class Media{
        //methods and properties
    }

    class Journalism extends Media{

    }
?>

The code above will result in an error.

Q.12. What is the default end time for a session in PHP?

Answer: The default time for a PHP session is 10 minutes. It can be extended further programmatically.

Q.13. What is the difference between const and define in PHP?

Answer: Both const keyword and define function are used to create a constant in PHP. The difference is that const works at the compile time whereas define works at run time. That means, if for example, you use the const keyword inside a conditional statement, it will not work. If we need to declare constants in a class or an interface, then it can be done by using the const keyword. define function cannot be used for this.

Q.14. What is a REST API?

Answer: A REST API is an API that follows the architectural rules of REST (Representational State Transfer).

An API can be called a REST API if it follows the following things-

– The URLs should be user-friendly. They should not contain any query string or any action name like ‘create’ or ‘update’.
For example:

https://abc.com/project/1 (valid)
https://abc.com/fetch?project_id=1(invalid)

– Specific HTTP methods should be used for specific operations.

For fetching the resources – GET
For creating a resource – POST
For updating a resource – PUT
For deleting a resource -DELETE

– A REST API can return the response in multiple formats like JSON, array, or object. However, the most popular format is JSON.

Q.15. How to connect a MySQL database to a PHP script?

Answer: There are multiple ways to connect to a MySQL database in PHP.

Using the mysqli_connect function: This function takes four parameters and will return a mysqli object.

mysqli_connect("host_name", "user_name", "password", "database_name");

Using the object of the mysqli class: When we create a new object of the mysqli class and pass four arguments as above, we get a mysqli connection object.

Using PDO: PDO stands for PHP Data Objects.

Q. 16. How many data types are there in PHP?

Answer: There are a total of eight datatypes in PHP. They are categorized into three categories:

  1. Scalar Types
  2. Compound Types
  3. Special Types

Scalar types

A scalar type data type holds only a single value at a time. There are four scalar types in PHP:1

Integer: An integer data type can hold an integer value (either negative or positive but having no decimal point).

The range of an integer could lie between 2,147,483,648 and 2,147,483,647. Moreover, an integer can be decimal(having base 10), octal(base 8), or hexadecimal(base 16).

Example:

<?php
    $num1 = 4; //decimal value
    $num2 = 017; //octal value
    $num3 = 0x10; //hexadecimal value

    echo $num1 . "<br />";
    echo $num2 . "<br />";
    echo $num3;
?>

Output:

4
15
16

float: A number having a decimal point is called a floating point or a float number. A float data type can store a fractional number (negative or positive).

Example:

<?php
    $num1 = 1.47;
    $num2 = -0.17;

    echo $num1 . "<br />";
    echo $num2;
	
?>

Output:

1.47
-0.17

string: A string data type stores a non numeric value. It can have characters, numbers, and special symbols enclosed in single or double quotes.

Example:

<?php
	$str1 = "1234"; //Here 1234 is not a numeric value but a string.
	$str2 = "The sun rises in the east";
	$str3 = "a$g1";
	$str4 = "abcd";

	echo $str1 . "<br />";
	echo $str2 . "<br />";
	echo $str3 . "<br />";
	echo $str4;
?>

Output:

1234
The sun rises in the east
a$g1
abcd

There is a difference between a single-quoted and a double-quoted string. A double-quoted string evaluates the value of a variable used within the string, whereas a single quoted string does not.

<?php
	$f = "fruit";
	$str1 = "Mango is a $f";
	$str2 = 'Mango is a $f';

	echo $str1 . "<br />";
	echo $str2 . "<br />";
	
?>

Output:

Mango is a fruit
Mango is a $f

boolean: A boolean data type can only have one of the boolean values – TRUE or FALSE. If is often used in loops and conditional statements.

Example:

<?php
	$isActive = TRUE;
	
	if($isActive)
	{
		echo "The bulb is on";			
	}
	else
	{
		echo "The bulb is off";
	}

?>

Output:

The bulb is on.

Compound types

They can hold multiple values at a time. There are two compound data types in PHP:

Array: An array is a data type that can store multiple values at different indexes. Keep in mind that there are different types of array in PHP, but we are considering here only numeric indexed array. The indexing starts with 0 in a numeric indexed array.

Example:

<?php
	$arr = array('Mango', 'Apple', 'Banana', 'Orange');
	
	echo $arr[0]; //0 is the index here
?>

Output:

Mango

It should be noted that there are four elements in the array. So, the indexes would be 0(having Mango), 1(having Apple), 2(having Banana), 3(having Orange).

We can print the whole array using the inbuilt function print_r().

<?php
	$arr = array('Mango', 'Apple', 'Banana', 'Orange');
	print_r($arr);
?>

Output:

Array
(
[0] => Mango
[1] => Apple
[2] => Banana
[3] => Orange
)

Note: The last index of a numeric indexed array will always be one less than the length of the array. Here the length of the array is 4, so the last index is 3.

Object: An object is a data type that represents a class. It can store both a value and a function.

Example:

<?php
	class Student
	{
		
		private $name;
		private $class;
		
		function __construct($n, $h)
		{
			$this->name = $n;
			$this->hours = $h;	
		}

		function study()
		{
			echo $this->name . " studies " . $this->hours . " hours per day";
		}
	}

	$stud1 = new Student('Jerry', 5);
	$stud1->study();
?>

Output:

Jerry studies 5 hours per day.

Special types

There are two special type data types in PHP:

resource: A resource is used to store a reference to an external resource. For example, a database call.

NULL: It is a special data type that has only one value – NULL. If it is stored in a variable, the variable will have no value (Not even zero).

Example:

<?php
	$x = NULL;
	echo $x;
?>

There will be no output for this.

Q. 17. Is PHP a case-sensitive language?

Answer: PHP is a partially case-sensitive language. That means, in PHP variable names are case-sensitive but user-defined function names are case-insensitive.

Example for variables

<?php
	$x = "Hello";
	echo $X; //This will throw an error.
?>

Example for functions

<?php
	function greet(){
		echo "Hello";
	}
	
	GREEt();//This will work fine
?>

Q. 18. How to execute a PHP script from the command line?

Answer: Open the command prompt and head over to the directory where your PHP file exists. Now assuming that your file name is index.php, run the following command

php index.php

And it will execute the PHP file in the command line.

Q. 19. What are the rules for naming a PHP variable?

Answer: There are certain rules which must be followed when declaring a variable in PHP.
These are-

1. A variable must start with the $ sign, followed by the name of the variable.
2. A variable name must start with a letter or the underscore character.
3. A variable name cannot start with a number.
4. A variable name can only contain alpha-numeric characters and underscores (A-z, 0-9, and _ ). It cannot contain any other special symbol like *.

Q. 20. What is NULL?

Answer: NULL(or null) is one of the data types in PHP. When a variable contains no value then it is said to be containing a null value. A variable can be assigned a null value manually by assigning it ‘null’

Example:

$x = null;

Q. 21. What is the purpose of the break and continue statement?

Answer: Inside a loop, the break is used to make an instant termination at some point, while continue is used to skip the iteration.
However, break is also used in the switch statement.

Example for break statement.

<?php
	$i = 1;
	while($i <= 10){
		echo $i;
		if($i == 5){
			break;
		}
	}
?>

Output:

1234

Example for continue statement

<?php
	$i = 1;
	while($i <= 10){
		echo $i;
		if($i == 5){
			continue;
		}
	}
?>

Output:

1234678910

Q. 22. How to concatenate two strings in PHP?

Answer: In PHP, concatenation is done by using the dot(.) operator.

For example:

<?php
	echo "The sun " . "rises in the east";
	//or
	$direction = "east";
	echo "The sun rises in the " . $direction;
?>

Q. 23. How can PHP and JavaScript interact?

Answer: PHP and JavaScript cannot interact directly since JavaScript is a client-side language and PHP is a server-side language. However, information can be passed from JavaScript to PHP through ajax.

Q. 24. Name some of the popular frameworks in PHP.

Answer: Some of the common and most used frameworks of PHP are Laravel, CodeIgniter, Symphony, Zend, Phalcon, Yii, and Cakephp.

25. What are constructors and destructors in PHP?

Answer: Constructor and destructor are two of the magic methods in PHP.

A constructor is a function inside a class that gets called automatically
when a new object of the class is created. A constructor is defined by placing two underscores before the name construct.

A constructor in PHP is always defined with the name __construct().

<?php
	class Sample{
		public function __construct(){
			//code inside constructor
			echo "Hello";
		}
	}

	$obj = new Sample();
?>

Output:

Hello

On the other hand, a destructor gets called when the object is destroyed or the execution of the script has finished.
A destructor in PHP is always defined with the name __destruct()

<?php
	class Sample{
		public function __destruct(){
			//code inside constructor
			echo "Destructor called";
		}
	}

	$obj = new Sample();
	unset($obj);
?>

Output:

Destructor called

Q. 26. What are the different types of errors available in PHP?

There are four types of errors in PHP-

1. Notice Error
2. Parse Error
3. Warning Error
4. Fatal Error

Q. 27. What are the different types of Array in PHP?

There are three types of arrays in PHP-

1. Numeric Array: This type of array has values inside it which are placed at certain numeric indexes or keys. A numeric index
of an array always starts from 0.

Example:

<?php
	$arr = array("mango", "chair", 42, 1.2);
	echo $arr[2];
	
?>

Output: 42

2. Multidimensional array: It is an array that contains other arrays.

Example:

<?php
	$multiArr = array(
			array("1,2,3,4"),
			array("mango", "apple", "banana", "guava")	
			);
	echo $multiArr[1][1];	
?>

Output: apple

3. Associative array: It is an array in which we can define the keys as well.

Example:

<?php
    $arr = array("name" => "Jimmy", "country" => "Canada");

    echo $arr["name"];
?>

Output: Jimmy

Q. 28. What are the rules for declaring a variable in PHP?

Answer:

1. A variable name should start with the dollar sign. For example – $x.
2. A variable name must begin with a letter or underscore. It cannot start with a number.
3. A variable name cannot contain spaces within.
4. A variable name can contain letter numbers or underscore. For example – $my_class1.

29. How is it possible to the set an infinite execution time for PHP script?

Answer: The infinite execution time can be set by using the set_time_limit() function and passing an argument 0.

<?php
	set_time_limit(0);
?>

Q. 30. What is method overloading in PHP?

Method overloading is a concept that permits the making of methods with the same name but with different arguments within a class. But in PHP we cannot do that. However, it can be achieved with a magic method __call().

Example:

<?php
	class Geometry
	{
		function __call($name, $arg)
		{
			if($name == 'calculateArea')
			{
				if(count($arg) == 1)
				{
					return 3.14 * $arg[0];
				}
				if($count($arg) == 2)
				{
					return $arg[0] * $arg[1];
				}
				if($count($arg) == 0)
				{
					return 0;
				}
			}	
		}
	}

	$obj = new Geometry();
	echo $obj->calculateArea(7); //21.98
	echo "<br />";
	$obj->calculateArea(4, 5);
?>

Output:

21.98
20

Q. 31. What is GET and POST method in PHP?

Answer: GET and POST are two of the HTTP methods in PHP. These methods can have different meanings when talking in different contexts. For example, if we talk about REST APIs, GET method is used to fetch the current state of a resource whereas POST method is used to create a new resource. In general, GET method is not very secure as the information passed through this method appears in the URL. Sensitive information should not be passed on using this method. The POST method is comparatively more secure than the GET method.

Q. 32. What is Type hinting in PHP?

Answer: Type hinting is a practice to force a function to accept only specified types of arguments.

For example:
The given function must accept the argument of array type only.

<?php
	function displayItems(array $arr){
		if($arr != null)
		{
			foreach($arr as $key => $val)
			{
				echo $val . "<br />";		
			}
		}
	}

	displayItems(array("Mango", "Apple", "Banana", "Orange"));
?>

Output:

Mango
Apple
Banana
Orange

If you try to give some other type of argument to the function, it will throw an error.

Q. 33. What is cURL?

Answer: The full form of cURL is client URL. It is used to set up communication between different servers. In general, it is used often to consume APIs in PHP.

Q. 34. What is the purpose of @ in PHP?

Answer:

 

Q. 35. What is a cookie? How to create a cookie in PHP?

Answer: Whenever a user requests a web page, the server saves a small record on the user’s computer. It is called a cookie. A cookie stores the information about the user and it exists for a particular period of time. In PHP, we can create a cookie using the inbuilt function setcookie().

Its syntax is-

setcookie(cookie_name, cookie_value, time);

<?php
    $cookie_name = "cityname";
    $cookie_value = "Mumbai";
    setcookie($cookie_name , $cookie_value, time() + (86400 * 30));
?>

Q. 36. What are PHP’s popular Content Management Systems (CMS)?

Answer: WordPress, Joomla and Drupal are the most Content Management Systems in PHP.

Q. 37. Which function is used to upload a file in PHP?

The move_upload_file() function is used for this purpose. Its syntax is-

move_upload_file($filename, $destination);

Q. 38. What is the current version of PHP?

Answer: As of now the current version of PHP is 8.1

Q. 39. What is the use of ini_set() function?

Answer: There are some settings that are defined in the php.ini file. These settings decide how the script behaves. For example, the maximum upload size is defined in that file. If you want to change some settings in the file in a particular script, you can do that using the ini_set function.

Example:

<?php
	ini_set('display_errors', 1);
?>

In this script, the errors would be displayed if any. However, if you replace 1 with 0, they are disabled.

Q. 40. What is type casting?

Answer: Typecasting is a technique to convert a value to another data type.

Example:

<?php
	$num = (int)4.7; //typecasting fractional value to an integer.
	echo $num;
?>

Output:
4

Another Example:

<?php
	$val = (int)TRUE; //Typecasting boolean value to integer
	echo $val;
?>

Output:
1

Q. 41. What will be the output of the following PHP code?

<?php
	$a = "fruit";
	$fruit = "Mango";
	$b = $$a;

	echo $b;
?>

Output:

Mango.

Q. 42. How to convert an array to JSON in PHP?

Answer: JSON is a text notation that stands for JavaScript Object Notation. In PHP, an array can be converted to a JSON string by using the inbuilt function json_encode().

Example

<?php
	$data = array("message" => "Hello", "sender" => "john");
	$jsonData = json_encode($data);
	
	echo $jsonData;
?>

Output:

{“message”:”Hello”, “sender”:”john”}

Q. 43. What is the difference between a single-quoted and a double-quoted string?

Answer: In a double-quoted string, we can use variables, whereas in a single-quoted string, we cannot.

Example:

<?php
	$days = 7;

	$str = "There are $days in a week";
	echo $str;
?>

Output:

There are 7 days in a week.

Another Example:

<?php
	$days = 7;

	$str = 'There are $days in a week';
	echo $str;
?>

Output: There are $days days in a week.

Q. 44. What is a trait?

Ans: A trait is a collection of user-defined functions that can be used in a class(or multiple classes). Traits solve the problem of multiple inheritance in PHP.

Example

<?php
	trait CommonFunctions{
		function toSQLDate($normalDate)
		{	
			$newDate = "";
			$dateParts = explode("-", $normalDate);
			$newDate .= $dateParts[2] . "-" . $dateParts[1] . "-" . $dateParts[0];
		}
	}
?>

Any of the functions defined inside a trait can be used in a class by using the ‘use’ keyword.

<?php
	class User
	{
		use Commonfunctions;
	
		public function returnSQLDate($joiningDate)
		{
			return toSQLDate($joiningDate);
		}
	}	
	
	$vinne = new User();
	echo $vinee->returnSQLDate('2022-09-02');
?>

Q. 45 Is there any difference between a method and a function?

Answer: No, there is no big difference. The only difference is that a function is called a method if it is defined inside a class.

Q. 46 What are magic constants in PHP?

Answer: There are nine magic constants in PHP:

1. __LINE__: It return the current line number where it is used.

<?php
	echo "This is line number " . __LINE__;
?>

Output:

This is line number 2;

2. __FILE__: It returns the full file path. Suppose the file name is test.php, which is stored in D:\xampp\htdocs\sampleproject.

Suupose the code given below is sitting in a file named test.php.

<?php
	echo __FILE__;
?>

Output:

D:\xampp\htdocs\sampleproject\test.php

3. __DIR__: It returns the full directory path of the executed PHP file.

<?php
	echo __FILE__;
?>

Output:

D:\xampp\htdocs\sampleproject

4. __FUNCTION__: It returns the executed function name.

<?php
	function displayName()
	{
		echo "The function name is " . __FUNCTION__;
	}

	displayName();
?>

Output:

The function name is displayName

5. __CLASS__: It returns the class name in which it is used.

<?php
	class Student
	{
		function getNameOfClass()
		{
			echo "The class name is " . __CLASS__;
		}
	}

	$obj = new Student();
	$obj->getNameofClass();
?>

Output:

The class name is Student

6. __TRAIT__: It returns the name of the trait in which it is used.

<?php
	
	trait sampleTrait
	{
		function getNameOfTrait()
		{
			echo "The trait name is " . __TRAIT__;
		}
	}
	
	class Student
	{
		use sampleTrait;
	}

	$obj = new Student();
	$obj->getNameofTrait();
?>

Output:

The trait name is SampleTrait

7. __METHOD__: It returns the name of the method in which it is used inside a class.

<?php
	class Student
	{
		function Test()
		{
			echo "The method name is " . __METHOD__;
		}
	}

	$obj = new Student();
	$obj->Test();
?>

Output:

The method name is Test

8. __NAMESPACE__: It returns the name of the namespace in which it is used.

9. ClassName::class: It returns the full class name(including the namespace).

<?php
 
    namespace Computer_Sciecnec_Portal;
    class Engineer{ }
 
    echo Engineer::class;//Classname::class
 
?>

Output:

Engineer

Q. 47 What is the difference between include and require functions in PHP?

Answer: If a file that does not exist is included in the script using the include function, then it will throw a warning and the rest of the script will execute. But if a file that does not exist is included using the require function, a fatal error will be generated and the script will stop altogether.

Q. 48. What is the difference between exit and die?

Answer: Both of them are used to stop the execution of the script. The only difference is the number of letters used!

Q. 49. Which is the most used hashing method used in PHP?

Answer: The crypt() function is the most widely used method for hashing passwords.

Q. 50 Which operator is used for concatenation in PHP?

Answer: Concatenation is a process of combining different data types. In PHP, it is done through either the dot operator(.) or comma (,) in PHP. However, most of the people uses the dot operator.

Example:

<?php
    $days = 7;
    echo "There are " . $days . " in  a week"; 
?>

Output:

There are 7 days in a week.