fbpx
developer interview
Mariusz Interewicz Updated: 13 Sep 2022 8 min to read

25 PHP Interview Questions and Answers – Advanced & Medium Level

PHP is one of the most popular programming languages in the world. It is used in many computer science courses and degrees as the base programming language to teach web development.

Thus, it becomes the first programming language of many newbies to web development. So, you will receive a large number of applications when you are going to hire a PHP developer.

Yet, how do you select the best developer out of those applicants? To help you with the interview process, we have created a list of 25 PHP questions that can be used to test the PHP knowledge of an applicant covering a wide area. You can guarantee to find a talented PHP developer by asking these questions in the interview.

Medium (Regular) Level Questions

1. Is PHP a strongly typed or loosely typed language? Justify your answer.

PHP is a loosely typed programming language, meaning it’s not required to define the data type of the variable when declaring variables. (Ex: variables in C/C++ are strongly typed and must’ve been declared with the data type. ( int myVariable; ) ). You can assign a string to a certain variable at one point so that the variable is a string ($myVar = “Hello”;), and if you decide to assign an integer value to it later, you can do so, changing the same variable type as int ($myVar = 100; ).

$myVar = “Hello”;
echo $myVar;    //Result : Hello

$myVar = 100;
echo $myVar;    //Result : 100

2. We can use GET and POST HTTP methods to retrieve data from a form submission. What is the main difference between the above methods, and which method is more secure?

The GET method submits the data as a part of the URL, making it visible to everyone, which will pose a huge security risk when sensitive data is submitted (passwords). Moreover, data of a GET request can be bookmarked, cached, and stored in the browser history.

On the other hand, the POST method does not submit data as part of the URL, and it’s not cacheable or bookmarkable. Using the POST method is the better choice between these two methods.

3. What is the main difference between include and require in PHP?

Both include and require are used to add another script/file into a PHP file, utilizing re-usability and thus reducing file size and complexity.

Include will copy the data from the linked file when used. It will generate a warning (E_WARNING) if the linked file is unavailable, and then the rest of the script will continue.

Require will generate a Fatal Error if the linked file is not available and will halt the execution of the script.

4. How can you declare a constant variable in PHP?

By using the define() function. define(NAME, VALUE).

Ex :
define(“app_id”, 12546);
echo app_id;     //Result : 12546

5. Does the use of == (double equals) and === (triple equals) operators have any difference in PHP? If yes, explain.

Yes, while both are comparison operators, the use of == and === will not return the same output.

The == (loose comparison) operator will compare the given values/context regardless of its data type.

Ex:
$userID = 1001;
$userName = “1001”;

if ($userID == $userName ):
echo “Same values”;
else:
echo “Not the same”;
endif;

// Result: Same values

The === (strict comparison) operator will check if the given value and the data type are exactly the same.

Ex:
$userID = 1001;
$userName = “1001”;

if ($userID === $userName ):
echo “Same values”;
else:
echo “Not the same”;
endif;

// Result: Not the same

6. How many error types are there in PHP? Briefly explain each type.

There are four error types.

Fatal errors: The most critical error type in the code, and it will stop the execution of the script until the issue is fixed.

A fatal error can occur at startup, compile-time, or runtime.

Ex: A call to an undefined function can cause a fatal error.

function myfunc(){
return “this is my function”;
}
echo $getOutput = myfunction();

Parse errors: A parse error is caused by syntax errors in the code. Often it can be triggered by a missing or misused symbol. It will be a compile-time error, and the execution of the script will be stopped when it occurs.

Ex :
$varOne = 1;
$varTwo =

echo $varOne+$varTwo;

Warning errors: Warnings will not stop the execution of the script. Instead, it’ll skip the code with the issue, display the warning and continue the execution. While these errors may seem not critical, they should be treated as important since they can cause more significant issues in the future.

A good example will be the use of include with a missing linked file.

Notice errors: A bit similar to warnings, notice errors are minor issues that can be fixed easily and will not affect the execution of the script.

Ex: undefined variable error.

7. Briefly explain the __construct() method in PHP.

The __construct() method ( the constructor ) will be automatically called by PHP on each newly created object from a class and used to initialize the object properties.

Ex:

Class DbConnector{
   private $dbName;
   private $dbUser;
   private $dbPass;

   public function __construct($dbName, $dbUser, $dbPass){
      $this->dbName = $dbName;
      $this->dbUser = $dbUser;
      $this->dbPass = $dbPass;

            }
}

Can be used as,

$connect = new DbConnector(“my_database”, “root”, “”);

8. You’ll be provided with an array of numbers. How can you get the sum of those numbers without using a loop?

By using the array_sum() method. It’ll take the array name as one parameter and return the count of values. It can even be used with an associative array.

$ar = array(2,4,6,8,10,12,14);
$getCount = array_sum( $ar );
echo $getCount;

// Result : 56

9. PHP provides a built-in super global variable that contains information about headers, paths, and script locations. Identify that global variable and how you can use it to display the server IP address?

Variable is = $_SERVER;

The following code can be used to display the IP address of the server using PHP and $_SERVER[‘SERVER_ADDR’].

$getIP = $_SERVER[‘SERVER_ADDR’];
echo $getIP;

10. How can you display the current date (date/month/year) using PHP?

PHP comes with a built-in function named date(), which accepts two parameters, format and timestamp.

$getDate = date(“j / n / Y”);

Advanced level questions

11. We can use “echo” or “print” in PHP to display an output. Does “echo” and “print” have any differences? If yes, explain.

Yes, while both echo and print seem to behave similarly, there are a few minor differences.

Ex :
$userName = “Elliot”;

echo $userName; // Result: Elliot
print $userName; // Result: Elliot

– Echo has no return value ( return type is void ) while print always has a return value of 1. This return value provides the ability to use print in expressions.

 

Ex :
$userName = “Elliot”;

$outputEC = echo $userName; // Result: Parse error: syntax error, unexpected T_ECHO

$outputPR = print $userName; // Result: Elliot
echo $outputPR; // Result : 1

– Even though we can provide multiple arguments into echo, print can utilize only one argument.

Ex:
$userName = “Elliot”;
$userRole = “SysAdmin”;
$userLevel = “Level-2”;

echo $userName , $userRole, $userLevel;

//Result : ElliotSysAdminLevel-2

print $userName , $userRole, $userLevel;

//Result : PHP Parse error: syntax error,

-* Echo is somewhat faster than print. (marginally faster).

12. You have a field for file uploads in a form you’ve created. But when you try to submit the form, you get an error with “UPLOAD_ERR_INI_SIZE.” What should be done to fix the issue?

The error UPLOAD_ERR_INI_SIZE is caused because the uploaded file size exceeds the maximum allowed file size limit in the php.ini configuration file. Change upload_max_filesize (declared in megabytes) in the php.ini file to change the maximum allowed file size.

Ex : upload_max_filesize = 64M

13. What is the use of the in_array() function in PHP?

The in_array() function is used to search for a value inside a string. It can be used to perform a case-sensitive search by setting the third parameter as TRUE.

Syntax : in_array(search_term, array_name, type_parameter);

Ex :
$myArray = array(“Elliot”, “Parker”,”Hardison”,8958);

if( in_array(“Elliot”), $myArray, TRUE ):
echo “Elliot is here”;
Endif;

14. What inbuilt function can be used to create web safe URLs that will convert the URLs to ASCII standard?

The urlencode() function can be used to achieve this.

Ex :
$safeURL = urlencode (“https://www.google.com/search?q=php+8”);
echo $safeURL;

//Result :

https%3A%2F%2Fwww.google.com% 2Fsearch%3Fq%3Dphp%2B8

15. How can you enable error reporting in PHP without modifying server files such as php.ini when using apache as the server?

It’s possible by adding show error options in the code at the top of the script and enabling error reporting in the .htaccess file.

Include the following lines in your script,

ini_set(‘display_errors’, ‘1’);
ini_set(‘display_startup_errors’, ‘1’);
error_reporting(E_ALL);

Then, include this line in the .htaccess file.
php_flag display_errors 1

16. You can use inheritance by using extend to another class inside your PHP script. However, there is a type of class that does not provide the ability to use with extend. How can we prevent the inheritance of a specific class in PHP?

By using the final keyword in the class.

class myFirst {
private $myName = “Sheldon”;
}
final class mySecond{
private $myEmail = “[email protected]”;
}
class myThird extends mySecond{
function getMyinfo(){
$myAddress = “address”;
}

// use of extends mySecond will throw an error, PHP Fatal error: Class myThird may not inherit from final class (mySecond)

17. PHP does not natively support multiple inheritance. How can you implement features of multiple inheritance in PHP?

By using interfaces (or using Traits).

18. Imagine you have been assigned to a project someone else has been working on, and you found an operator with ( += ) in one file. What will be the use of += in the code?

( Ex :
$myVariableOne = 70;
$myVariableTwo = 20;
$myVariableOne += $myVariableTwo;
)

The operator += is a shorthand for adding another value to the original value and saving the final result in the original variable.
In the above example, we can write,,
$myVariableOne += $myVariableTwo;
as
$myVariableOne = $myVariableOne + $myVariableTwo;
So, in the end, the value of $myVariableOne will be 90.
*Works only for numeric values. You should use ( .= ) for strings.

19. Imagine you need to remove a single element from an array. Briefly explain how to accomplish it.

We can use two different methods, which will provide two different results.

We can use the unset() method to remove the element without affecting the array indexes.

$myTeam = [0 => “Leonard”, 1 => “Howard”, 2 => “Sheldon”, 3 => “Raj”];
print_r($myTeam);
//Result : Array ( [0] => Leonard [1] => Howard [2] => Sheldon [3] => Raj )

unset($myTeam[2]);
print_r($myTeam);
//Result : Array ( [0] => Leonard [1] => Howard [3] => Raj )

The element is removed, but array indexes are unchanged.

By using array_splice() method. Unlike the unset() method, array_splice() uses offset and the length of the array. If provided, it removes the elements and reindexes or replaces the elements from the replacement array.

$myTeam = [0 => “Leonard”, 1 => “Howard”, 2 => “Sheldon”, 3 => “Raj”];
print_r($myTeam);
//Result : Array ( [0] => Leonard [1] => Howard [2] => Sheldon [3] => Raj )

array_splice($myTeam, 2, 1);
print_r($myTeam);

//Result : Array ( [0] => Leonard [1] => Howard [2] => Raj )

array_splice($myTeam, 2, 2);
print_r($myTeam);

//Result : Array ( [0] => Leonard [1] => Howard )

20. How can you pass a variable by reference?

By using the ampersand symbol ( & ),

$myVarOne = &$myVarTwo;

Ex :
$myVarOne = “Hello”;
$myVarTwo = “Hello Sheldon”;
echo $myVarOne; // Result : Hello

$myVarOne = &$myVarTwo;
echo $myVarOne; // Result : Hello Sheldon

21. Explain the use of the self keyword in PHP and the difference between this and self.

Self is used to access static methods and properties.

$this refers to the current object, while self refers to the current class. $this ( $this->userName )is used to access non-static methods and properties , while self ( self::$userName ) is used to access static methods and properties.

22. We can use die() and exit() to terminate the execution of the current script. What will be the difference between die() and exit()?

There is no difference. PHP documentation mentions that die() will be an equivalent to exit(). The method die() is an alias for exit().

Since PHP has a close resemblance to C and Perl, exit() came from C, while die() came from Perl.

23. What will be the importance of using @ operator with expressions in PHP?

As mentioned in the PHP documentation, it’s the error control operator. When it is prepended to an expression, any diagnostic error that might be generated by that expression will be suppressed.

24. How can you determine whether a PHP session has already been started?

By using the session_status() method.

$getSessionState = session_status();
if( $getSessionState === PHP_SESSION_NONE ):
session_start();
endif;

it’ll return,

PHP_SESSION_DISABLED (or 0 ) if sessions are disabled, PHP_SESSION_NONE (or 1 ) if the session is not active, and PHP_SESSION_ACTIVE (or 2 ) when the session has already started.

 

25. Briefly explain the difference between print_r() and var_dump() in PHP.

The print_r() function will take a variable or expression as a parameter and display structured information about the variable/expression in a human-readable format.

Ex :
$myArray = array( 121, 232, array( “Rick”, “Morty” ) );
print_r($myArray);

//Result

array1

On the other hand, var_dump() will take a variable/expression as a parameter and dump the data with data types in a structured format of type and value. Arrays and objects are explored recursively, with values to show the structure.

Ex:
$myArray = array( 121, 232, array( “Rick”, “Morty” ) );
var_dump($myArray);

//Result

array2

 

Call to action
If you are looking for PHP developers to join your company, we’ll be happy to help you build your dream team. Tell us about your needs and our specialists will present possible cooperation models.
default avatar asper brothers

Share

SUBSCRIBE our NEWSLETTER

Are you interested in news from the world of software development? Subscribe to our newsletter and receive a list of the most interesting information.

    ADD COMMENT

    RELATED articles