35+ Important PHP Interview Questions and Answers to Prepare For

how to answer PHP Interview Questions
Summary:

Here are essential PHP interview questions and answers to practice before your big day, for both experienced developers and junior candidates.

Need to test a developer’s PHP skills, or have a PHP interview coming up?

A few of the best developers within our network share their top PHP interview questions, answers, and interview tips to help test a developer’s PHP knowledge and expertise.

Aside from the PHP interview questions and answers to know below, don’t forget to brush up on how to answer behavioral interview questions and how to show off other hard skills and soft skills (e.g., cross-cultural communication skills, collaboration skills, time management skills).

Without further ado, let’s jump in!

Looking to hire the best remote developers? Arc can help you:

⚡️ Get instant candidate matches without searching
⚡️ Identify top applicants from our network of 350,000+
⚡️ Hire 4x faster with vetted candidates (qualified and interview-ready)

Try Arc to hire top developers now →

1. What’s the difference between the include() and require() functions?

They both include a specific file but on require the process exits with a fatal error if the file can’t be included, while include statement may still pass and jump to the next step in the execution.

2. How can we get the IP address of the client?

This question might show you how playful and creative the candidate is because there are many options. $_SERVER["REMOTE_ADDR"]; is the easiest solution, but the candidate can write x line scripts for this question.

3. What’s the difference between unset() and unlink()?

unset() sets a variable to “undefined” while unlink() deletes a file we pass to it from the file system.

4. What is the output of the following code:

$a = '1';
$b = &$a;
$b = "2$b";
echo $a.", ".$b;

During the interview of a potential candidate I am aiming to understand how updated they are with the new language features as well as their level of understanding of basic operations. In my opinion, this will define how good a developer will become in the future.

Agli Pançi, Lead Developer of Manoolia and the co-founder of Zero1 Community Albania

5. What are the main error types in PHP and how do they differ?

In PHP there are three main type of errors:

  • Notices – Simple, non-critical errors that are occurred during the script execution. An example of a Notice would be accessing an undefined variable.
  • Warnings – more important errors than Notices, however the scripts continue the execution. An example would be include() a file that does not exist.
  • Fatal – this type of error causes a termination of the script execution when it occurs. An example of a Fatal error would be accessing a property of a non-existent object or require() a non-existent file.

Understanding the error types is very important as they help developers understand what is going on during the development, and what to look out for during debugging.


Struggling with interview prep? Meet senior developers from Amazon, Microsoft, and Google now on Codementor. They’ll help you tackle coding challenges, practice interviews, and sharpen your skills in live 1:1 sessions.

Book a session with our interview prep tutors today! Your first 15 minutes are free.

Explore our other software development interview questions and answers to prep for your next remote job.


6. What is the difference between GET and POST?

  • GET displays the submitted data as part of the URL, during POST this information is not shown as it’s encoded in the request.
  • GET can handle a maximum of 2048 characters, POST has no such restrictions.
  • GET allows only ASCII data, POST has no restrictions, binary data are also allowed.
  • Normally GET is used to retrieve data while POST to insert and update.

Understanding the fundamentals of the HTTP protocol is very important to have for a PHP developer, and the differences between GET and POST are an essential part of it.

7. How can you enable error reporting in PHP?

Check if “display_errors” is equal “on” in the php.ini or declare “ini_set('display_errors', 1)” in your script.

Then, include “error_reporting(E_ALL)” in your code to display all types of error messages during the script execution.

Enabling error messages is very important especially during the debugging process as one can instantly get the exact line that is producing the error and can see also if the script in general is behaving correctly.

8. What are Traits?

Traits are a mechanism that allows you to create reusable code in languages like PHP where multiple inheritance is not supported. A Trait cannot be instantiated on its own.

It’s important that a developer knows the powerful features of the language (s)he is working on, and Trait is one of such features.

9. Can the value of a constant change during the script’s execution?

No, the value of a constant cannot be changed once it’s declared during the PHP execution.

One of the most important things I watch out is the creativity of the person I interview. I try to catch the developers who are constantly learning new things, they are driven by curiosity and also very creative, not just in problem solving but in general too. I mostly ask about PHP and PostgreSQL (I use this combo most of the time).

Laszlo Levente Mári, ex-Google front-end engineer

10. Can you extend a Final defined class?

No, you cannot extend a Final defined class. A Final class or method declaration prevents child class or method overriding.

11. What are the __construct() and __destruct() methods in a PHP class?

All objects in PHP have Constructor and Destructor methods built-in. The Constructor method is called immediately after a new instance of the class is being created, and it’s used to initialize class properties. The Destructor method takes no parameters.

Understanding these two in PHP means that the candidate knows the very basics of OOP in PHP.

12. How we can get the number of elements in an array?

The count() function is used to return the number of elements in an array.

Understanding of arrays and array related helper functions is important for any PHP developer.

13. How would you declare a function that receives one parameter name hello?

If hello is true, then the function must print hello, but if the function doesn’t receive hello or hello is false the function must print bye.

<?php
function showMessage($hello=false){
  echo ($hello)?'hello':'bye';
}
?>

In this question, you can evaluate if the developer knows how to declare a function and how they would manage the fact of the parameter can or cannot be on the function call. You can also evaluate if the developer knows the if syntax and how to print text(echo function).

14. The value of the variable input is a string 1,2,3,4,5,6,7. How would you get the sum of the integers contained inside input?

<?php
echo array_sum(explode(',',$input));
?>

The explode function is one of the most used functions in PHP, so it’s important to know if the developer knows this function. There is no unique answer to this question, but the answer must be similar to this one.

15. Suppose you receive a form submitted by a post to subscribe to a newsletter. This form has only one field, an input text field named email. How would you validate whether the field is empty? Print a message "The email cannot be empty" in this case.

<?php
if(empty($_POST['email'])){
  echo "The email cannot be empty";
}
?>

In this question, the candidate should be evaluated on his/her knowledge about forms management and validation. There is not unique answer for this question, but it must be similar to this one.

15. How would you implement a class in the following scenario?

Suppose that you have to implement a class named Dragonball. This class must have an attribute named ballCount (which starts from 0) and a method iFoundaBall. When iFoundaBall is called, ballCount is increased by one. If the value of ballCount is equal to seven, then the message You can ask your wish is printed, and ballCount is reset to 0. How would you implement this class?

<?php
class dragonBall{
  private $ballCount;

  public function __construct(){
    $this->ballCount=0;
  }

  public function iFoundaBall(){
    $this->ballCount++;
    if($this->ballCount===7){
      echo "You can ask for your wish.";
      $this->ballCount=0;
    }
  }
}
?>

This question will evaluate a candidate’s knowledge about OOP.

16. What are the 3 scope levels available in PHP and how would you define them?

Private – Visible only in its own class
Public – Visible to any other code accessing the class
Protected – Visible only to classes parent(s) and classes that extend the current class

This is important for any PHP developer to know because it shows an understanding that building applications is more than just being able to write code. One must also have an understanding about privileges and accessibility of that code.

There are times protected variables or methods are extremely important, and an understanding of scope is needed to protect the integrity of the data in your application along with provide a clear path through the code.

17. What are getters and setters and why are they important?

Getters and setters are methods used to declare or obtain the values of variables, usually private ones. They are important because it allows for a central location that is able to handle data prior to declaring it or returning it to the developer.

Within a getter or setter one is able to consistently handle data that will eventually be passed into a variable or additional functions. An example of this would be a user’s name. If a setter is not being used and the developer is just declaring the $userName variable by hand, you could end up with results as such: "kevin""KEVIN""KeViN""", etc.

With a setter, the developer can not only adjust the value, for example, ucfirst($userName), but can also handle situations where the data is not valid such as the example where "" is passed. The same applies to a getter – when the data is being returned, it can be modifyed the results to include strtoupper($userName) for proper formatting further up the chain.

This is important for any developer who is looking to enter a team-based / application development job to know. Getters and setters are often used when dealing with objects, especially ones that will end up in a database or other storage medium.

Because PHP is commonly used to build web applications, developers will run across getters and setters in more advanced environments. They are extremely powerful yet not talked about very much. It is impressive if a developer shows that he/she knows what they are and how to use them early on.

18. What does MVC stand for and what does each component do?

MVC stands for Model View Controller. The controller handles data passed to it by the view and also passes data to the view. It’s responsible for the interpretation of the data sent by the view and dispersing that data to the appropriate models awaiting results to pass back to the view. Very little, if any business logic should be occurring in the controller.

The model’s job is to handle specific tasks related to a specific area of the application or functionality. Models will communicate directly with your database or other storage system and will handle business logic related to the results.

The view is passed data by the controller and is displayed to the user.

Overall, this question is worth knowing as the MVC design pattern has been used a lot in the last few years and is a very good design pattern to know. Even with more advanced flows that go down to repositories and entities, they still are following the same basic idea for the Controller and View.

The Model is typically just split out into multiple components to handle specific tasks related to database data, business logic etc. The MVC design pattern helps draw a better understanding of what is being used, as a whole, in the industry.

19. How does one prevent the following Warning ‘Warning: Cannot modify header information – headers already sent’ and why does it occur in the first place?

The candidate should not output anything to the browser before using code that modifies the HTTP headers. Once the developer calls echo or any other code that clears the buffer, the developer can no longer set cookies or headers.

That is also true for error messages, so if an error happens before using the header command and the INI directive display_errors is set, then that will also cause that error to show.

20. What are SQL Injections, how do you prevent them and what are the best practices?

SQL injections are a method to alter a query in a SQL statement send to the database server. That modified query then might leak information like username/password combinations and can help the intruder to further compromise the server.

To prevent SQL injections, one should always check & escape all user input. In PHP, this is easily forgotten due to the easy access to $_GET & $_POST, and is often forgotten by inexperienced developers. But there are also many other ways that users can manipulate variables used in a SQL query through cookies or even uploaded files (filenames). The only real protection is to use prepared statements everywhere consistently.

Do not use any of the mysql_* functions which have been deprecated since PHP 5.5 ,but rather use PDO, as it allows you to use other servers than MySQL out of the box. mysqli_* are still an option, but there is no real reason nowadays not to use PDO, ODBC or DBA to get real abstraction. Ideally you want to use Doctrine or Propel to get rid of writing SQL queries all together and use object-relational mapping which binds rows from the database to objects in the application.

21. What does the following code output?

$i = 016;
echo $i / 2;

The Output should be 7. The leading zero indicates an octal number in PHP, so the number evaluates to the decimal number 14 instead to decimal 16.

22. Why would you use === instead of ==?

If you would want to check for a certain type, like an integer or boolean, the === will do that exactly like one would expect from a strongly typed language, while == would convert the data temporarily and try to match both operand’s types.

The identity operator (===) also performs better as a result of not having to deal with type conversion. Especially when checking variables for true/false, one should avoid using == as this would also take into account 0/1 or other similar representation.

23. What are PSRs? Choose 1 and briefly describe it.

PSRs are PHP Standards Recommendations that aim at standardizing common aspects of PHP Development.

An example of a PSR is PSR-2, which is a coding style guide. More info on PSR-2 here.

24. What PSR Standards do you follow? Why would you follow a PSR standard?

Developers should follow a PSR because coding standards often vary between developers and companies. This can cause issues when reviewing or fixing another developer’s code and finding a code structure that is different from yours. A PSR standard can help streamline the expectations of how the code should look, thus cutting down confusion and in some cases, syntax errors.

25. Do you use Composer? If yes, what benefits have you found in it?

Using Composer is a tool for dependency management. The candidate can declare the libraries your product relies on and Composer will manage the installation and updating of the libraries. The benefit is a consistent way of managing the libraries depended on so less time is spent managing the libraries.

Extra PHP Interview Questions

Special thanks to Ben Edmunds for the following extra questions:

  • What’s the difference between using mysql_ functions and PDO?
  • Describe how inheritance works with PHP.
  • Do you know what the PHP-FIG is? Describe it, describe the PSRs you know.
  • What classes would you create to build a basic Twitter-style status system with OOP?
  • What frameworks are you experienced in?
  • What frameworks do you prefer? Why?
  • Thoughts/experience with unit testing?

Exercise:

Build the Twitter style status system mentioned above using PHP (it doesn’t have to run or be error-free). This should be an MVP and take less than 30 minutes.

Other PHP concepts

Our PHP interview questions here aren’t all-encompassing. Here are some additional concept that PHP developers should know:

  • Using htmlspecialchars namespaces and shorthand array styles []
  • How to optimize code & how to pass user-supplied data to SQL to avoid injection.

Conclusion

If you’re looking for a PHP developer for your e-commerce site, desktop application, or more, we hope these 25+ interview questions get you on the right track to finding a top developer for your needs.

When talking about PHP, don’t forget PHP frameworks like Laravel, Symfony, and others.

Good luck!

You can also explore HireAI to skip the line and:

⚡️ Get instant candidate matches without searching
⚡️ Identify top applicants from our network of 350,000+ with no manual screening
⚡️ Hire 4x faster with vetted candidates (qualified and interview-ready)

Try HireAI and hire top developers now →

Written by
Arc Team