PHP Top Interview Questions and Answers.

PHP or Hypertext Preprocessor, is a general-purpose programming language. It is the most preferred language for web development, which is why many organizations look for skilled and experienced PHP professionals.

Q1. What is PHP?

Ans. PHP stands for Hypertext Preprocessor. It is a web-based scripting language used to create dynamic and interactive web pages. The syntax of PHP resembles Perl or C. It can perform any task related to server-side programming. A PHP file consists of tags and ends with the extension “.php.” PHP code can be embedded into HTML code. It can also be used with web content management, frameworks, and template systems.

PHP is a simple language to work on, even a new user can work on it. It offers multiple advanced features for professional developers, allowing them to develop efficient codes using its distinctive features. 

Q2. Explain the different types of data types in PHP.

Ans. PHP supports the following eight data types to construct the variables:

 Data typeDescription
1IntegersIt includes whole numbers (without a decimal point).
2BooleansThese have only two possible values, either true or false.
3DoublesFloating-point numbers, like 23.6 or 2.32679.
4ArraysNamed and indexed collections of other values
5StringsSequences of characters
6ObjectsInstances of programmer-defined classes, which can package up both other kinds of values and functions that are specific to the class
7NULLSpecial type that only has one value, NULL
8ResourcesSpecial variables that hold references to resources external to PHP

Q3. What are the features of PHP?

Ans. PHP has some unique features, which include:

  • Open-source
  • Platform Independent
  • Case sensitive
  • Flexibility
  • Efficiency
  • Third-party application support and security
  • Interpreted

 Q4. Why do we use PHP?

Ans. There are various reasons to use PHP for server-side programming:

  • It is a free language with no licensing fees; the cost of using it is minimal.
  • It supports multiple databases, including MySQL that is also a free source.
  • It is easier to create a website

Q5. Is PHP a loosely typed language?

Ans. Yes, it is a loosely typed language. It is not required to declare a variable type to declare a variable.

In PHP, if you declare a variable, then you don’t have to worry about what type of data would be stored in that variable. If you declare a variable called $String then it is not necessary to assign a string value, you can assign an integer value also.

Example:

$var=”Hello”: //String

$var= 20; //Integer

Q6. What are the different PHP Frameworks?

Ans. Following are the popular frameworks:

  • CodeIgniter
  • Yii 2
  • CakePHP
  • Zend Framework
  • Symfony
  • Phalcon
  • PHPixie
  • FuelPHP

 Q7. What are the characteristics of PHP variables?

Ans. Following are the characteristics:

  • Each variable is denoted by a dollar sign ($).
  • The value of a variable is the value of its most recent assignment.
  • Variables are assigned with “=” operator, where the variable is on the left-hand side and expression is on the right-hand side.
  • Variables can be but do not need to be declared before the assignment.
  • Variables do not have an intrinsic type; it does not know its variable type and can be assigned with any variable type.
  • Variables that are used in the code before they are assigned, have a default value.
  • PHP variables are Perl-like.

Q8. What does PEAR mean?

Ans. PEAR stands for “PHP Extension and Application Repository”. PEAR provides a structured library of open-source code to PHP users.

 Q9. What is the difference between PHP 4 and PHP 5?

Ans. The differences between PHP4 and PHP5 are:

PHP 4PHP 5
In PHP 4, the Constructor has the same name as the class name.The Constructors are named as _construct and Destructors are named as _destruct().
Objects are passed by value.References pass all objects.
It does not declare a class or method as abstract.Allows to have static Methods and Properties in a class
It doesn’t have static methods and properties in a class.Static methods are available. 
Don’t have exception handling.Introduces exception handling.
No new default extensions.It has new default extensions: XML, DOM, XSL, etc.
PHP 4 does not support the OOPs concept and Zend engine 1 is used.PHP 5 supports the OOPs concept and Zend engine 2 is used.
Memory consumption is more.Consumption of memory is less.

 Q10. What is the difference between echo and print?

Ans. Both echo and print methods are used to print the output in the browser, but the difference between them is echo does not return any value after printing the output, and it is also faster than the print method. The print method is slower because it returns the Boolean value after printing the output.

Syntax:

  • echo “PHP Developer”;
  • $n = print “Java Developer”;

Q11. How can we execute PHP script using the command line?

Ans. PHP command is used in the command line to execute a PHP script. If you are using the file name, i.e. test.php the php test.php command is used to run the script from the command line.

Q12. What is required to use the image function?

Ans. To use the image function, we will need the GD library.

Q13. Mention the popular Content Management Systems (CMS) in PHP?

Ans. Following are some popular Content Management Systems (CMS):

  • WordPress
  • Shopify
  • Drupal
  • Joomla
  • Wix
  • Magento

Q14. How to declare an array?

Ans. There are three types of arrays that you can declare i.e. numeric, multidimensional and associative arrays.

  1. //Numeric

Array

  1. $computer = array(“Dell”,

“Lenovo”, “HP”);

  1. //Associative

Array

  1. $color = array(“Sithi”=>”Red”,

“Amit”=>”Blue”, “Mahek”=>”Green”);

  1. //Multidimensional

Array

  1. $courses = array ( array(“PHP”,50),

array(“JQuery”,15), array(“AngularJS”,20) );

Q15. Mention some of the constants in PHP and their purpose.

Ans. The following are some constants:

  • _LINE_: The current line number of the file.
  • _FILE_: It represents the file’s full path and file name. If used inside an include, it will return the name of the included file.
  • _FUNCTION_: It returns the function name.
  • _CLASS_: It returns the class name as it was declared.
  • _METHOD_: It represents the method of the class.

Q16. Explain the uses of explode() and implode() functions.

Ans. The explode() function is used to split by a specified string into pieces i.e. it breaks a string into an array.

Example: If you have a string

$str = “JOHN”:

Now, divide string into an array

$arr = explode(“,”, $str);

“,” will separate the string into an array

And put the resulting array into the variable “arr”

Use print_r ($arr); to print the array

Array(

[0] => J

[1] =>O

[2] => H

[3] => N

)

which is equal to:

$arr = Array (“J”,”O”,”H”,”N”)

An implode() function is used to join the elements of an array to a string. It returns a string from an array, and it is remembered as “array to string.”

Take an array like this $arr = Array (“J”,”O”,”H”,”N”);

Convert it into a string by putting the separator ‘-‘ between each array element.

$str = implode(“-“,$arr);

So your resulting string variable $str will contain:

J-O-H-N

Syntax:

$text = “She is beautiful”;

print_r (explode(” “,$text));

$strarr = array(‘Pen’,’Pencil’,’Eraser’);

echo implode(” “,$strarr);

Q17. Explain the PHP $ and $$ variables?

Ans. The “$” variable is a standard variable that stores values such as string, float, integer, etc.

The “$$” variable is used to store the value of $variable inside it.

<?php

$name=”Joe”;

${$name}=”Merry”;

${${$name}}=”Dolcie”;

echo $name. “<br>”;

echo ${$name}. “<br>”;

echo $Cat. “<br>”;

echo ${${$name}}. “<br>”;

echo $Dog. “<br>”;

?>

Output:

Joe

Merry

Merry

Dolcie

Dolcie

Q18. Explain the difference between GET and POST methods?

Ans. This is one of the most commonly asked PHP interview questions.

There are two ways to send information via browser client to the web server:

  • The GET method
  • The POST method
GET methodPOST method
The GET method produces a long string that appears in the server logIt is restricted to send only 1024 charactersIt is not used to send binary data such as word document or images to the server$_GET is used to access all the sent information using GET methodThe POST method has no restriction to any data size to be sentIt can be used to send both binary data as well as ASCII dataIn this method, security depends on the HTTP protocol because the data sent by the POST method goes through an HTTP header.$_POST associative array is provided by the PHP to access all the sent information using POST method

Q19. Explain type casting and type juggling.

Ans. Type casting is defined as assigning a particular type of data type to the variable.

Example:

$foo = ‘1’;

echo gettype($foo); // outputs ‘string’

settype($foo, ‘integer’);

echo gettype($foo); // outputs ‘integer’

In type juggling, the variable type changes automatically with the value assigned to the variable, as PHP does not support the variable declaration.

Example:

<?php

$foo = “0”; // $foo is string (ASCII 48)

$foo += 2; // $foo is now an integer (2)

$foo = $foo + 1.3; // $foo is now a float (3.3)

?>

Q20. Can you extend a Final defined class?

Ans. No, You cannot extend the Final method. The final class prevents child class and method overloading.

Example of Final method:

<?php

class ParentClass {

public function test() {

echo “ParentClass::test() called\n”;

}

final public function moreTesting() {

echo “ParentClass::moreTesting() called\n”;

}

}

class ChildClass extends ParentClass {

public function moreTesting() {

echo “ChildClass::moreTesting() called\n”;

}

}

// Results in Fatal error: Cannot override final method ParentClass::moreTesting()

?>

Q21. How to make a connection with MY SQL server?

Ans.  If you want to connect with the MS SQL server, you have to provide the MS SQL hostname, username, and password in the mysqli_connect() method.

Example:

<?php

$serverName = “serverName\\sqlexpress”; //serverName\instanceName

$connectionInfo = array( “Database”=>”dbName”, “UID”=>”userName”, “PWD”=>”password”);

$conn = sqlsrv_connect( $serverName, $connectionInfo);

if( $conn ) {

echo “Connection established.<br />”;

}else{

echo “Connection could not be established.<br />”;

die( print_r( sqlsrv_errors(), true));

}

?>

Q22. Explain the difference between mysqli_connect and mysqli_pconnect.

Ans. mysqli_connect () function looks for the existing persistence connection, and if it does not find the existing connection, then it will create a new database connection and terminate the connection at the end of the script.

Example:

$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 diminished in the new version of PHP, but it is possible to create a persistent connection using the mysqli_connect() function with the prefix p.

Q23. How do we access the data transfer through the URL with the POST method?

Ans. We need to use the $_POST array to access the data transfer through the URL.

Let’s assume we have a form field named ‘var’ on the form. When the user clicks submit to the posting form, then it is easy to access the value:

$_POST[“var”];

Q24. What is the process to check if a given variable is empty?

Ans. We can use the empty() function to check whether a variable is empty.

Q25. Explain the unlink() function in PHP.

Ans. The unlink() function is used for file system handling. It also deletes the file started as the entry.

Q26. Explain what does the unset() function mean?

Ans. The unset() function is introduced for variable management. It helps to make a variable undefined.

Q27. What is the process to automatically run off incoming data?

Ans. If we want to run off incoming data automatically, We have to allow the Magic quotes entry in the PHP configuration file.

Q28. Describe what the function get_magic_quotes_gpc() means.

Ans. In PHP, the function get_magic_quotes_gpc() describes whether the magic quotes are switched on.

Q29. Can we remove the HTML tags from the data?

Ans. Yes, we can. The strip_tags() function allows us to clean a string from the HTML tags.

Q30. What is the procedure to cast types in PHP?

Ans. The name of the output type has to be defined in parentheses before the variable, which is to be cast as follows:

* (int), (integer) – cast to integer

* (bool), (boolean) – cast to boolean

* (float), (double), (real) – cast to float

* (object) – cast to object

* (array) – cast to array

* (string) – cast to string

Q31. If the variable $var0 contains the value 500 and the $var1 is set to the character var0, what’s the value of $$var1?

Ans. $$var1 contains the value 500.

Q32. Explain what accessing a class via:: means.

Ans. In PHP, :: is used to access static methods where object initialization is not required.

Q33. In PHP, objects used are passed by value or passed by reference.

Ans. Objects used passed by value in PHP.

Q34. Which given code works faster?

Ans. Combining two variables as follows:

$variable1 = ‘Naukri’;

$variable2 = ‘Learning’;

$variable3 = $variable1.$variable2;

Or

$variable3 = “$variable1$variable2”;

$variable3 will contain “Shiksha Online”. The first code works faster than the second code.

Q35. What is the possible way to generate a session id?

Ans. We can generate a session id using cookies or URL parameters.

Q36. Explain what Persistent Cookie is.

Ans. In PHP, a persistent cookie is gathered in a cookie file on the browser’s computer. Cookies are automatically stored and deleted while we close browse.

Q37. At what phase do sessions end in PHP?

Ans. Sessions end automatically when the PHP script is completed with execution but can be manually ended using the session_write_close().

Q38. Explain what $GLOBALS is.

Ans. In PHP, $GLOBALS is an associative array including references to all variables currently defined in the script’s global scope.

Q39. What does $_SERVER mean?

Ans. $_SERVER is an array, including data created by the web server, such as paths, headers, and script locations.

Q40. What do $_FILES mean?

Ans. $_FILES is an associative array of items sent to the current script via the HTTP POST method.