Vijay Singh Khatri | 11 Oct, 2022

Top 53+ PHP Interview Questions and Answers [2024]


Hypertext Preprocessor (PHP) is a popular scripting language used for web development. This open-source language was created in 1994 and is now managed by the PHP group. The language can run on various platforms such as Windows, Linux, and MacOSX, and is compatible with most of the servers used today like Apache and IIS.

If you aspire to be a PHP developer, you’ll need to know it thoroughly. Here, we’ve made a collection of the top PHP interview questions and answers to help you. We’ve divided these questions into basic, intermediate, and advanced PHP interview questions.

PHP Interview Questions and Answers

Basic PHP Questions

1. What is PHP?

PHP is a general-purpose scripting language, mostly implemented in C and C++, and is often used in web development. It is a highly performant language as the code need not be compiled before execution. It is also free and open-sourced, and can be easily learned. PHP is also cost-effective as most web hosting servers support it by default.

Sample code:

<?PHP

echo'Good morning';

?>

Read this post to know about What is PHP?

2. What are the Features of PHP7.4?

Some new features in PHP7.4 are:

  • Preloading to further improve performance.
  • Arrays spread operator.
  • One line arrow functions (short closures) for cleaner code.
  • Typed properties in the class.
  • Formatting numeric values using underscores.
  • Extension development using FFI.
  • A better type of variance.

3. Explain the difference between $message and $$message?

$message is a regular variable, which has a fixed name and fixed value, whereas a $$message is a reference variable, which stores data about the variable. The value of $$message can change dynamically as the value of the variable changes.

4. What are magic constants?

Magic constants start and end with double underscores and are predefined constants that change their value based on context and usage. There are 9 magic constants in PHP:

__LINE__, __FILE__, __DIR__, __FUNCTION__, __CLASS__, __TRAIT__, __METHOD__, __NAMESPACE__, ClassName::class

5. What are the various data types in PHP?

The different data types in PHP in are:

  • String: a sequence of characters, e.g.," Hackr.io."
  • Float: a floating-point (decimal) number, e.g., 23.456
  • Integer: an integer, e.g. 12
  • Boolean: represents two states – true, false.
  • Object: stores values of different data types into single entity, eg. apple = new Fruit();
  • Array: stores multiple values of same type, eg. array("red", "yellow", "blue")
  • NULL: when no value is assigned to a variable, it can be assigned NULL. For example, $msg = NULL;

6. What is the isset() function?

The isset() function checks if the particular variable is set and has a value other than NULL. The function returns Boolean – false if the variable is not set or true if the variable is set. The function can check multiple values: isset(var1, var2, var3…)

7. What are the various PHP array functions?

There are many array functions, all of which are part of the PHP core:

Array Functions

Description

array()

Creates an array.

array_diff()

Compares arrays and returns the differences in the values.

array_keys()

Returns all the keys of the array.

array_reverse()

Reverses an array.

array_search()

Searches a value and returns the corresponding key.

array_slice()

Returns the specific parts of the array.

array_sum()

Sums all the values of an array.

count()

The number of elements of an array.

Find more functions on the PHP manual page.

8. Explain the difference between indexed and associative array.

Indexed Array

Associative Array

Has numeric keys or indexes

Each key has its value

Indexes start with 0 and are automatically assigned

Keys are assigned manually and can be strings too

Example:

$fruits = array(“orange”, “apple”, banana);

Here, orange is $fruits[0], apple is $fruits[1] and banana is $fruits[2]

Example:

$empdetails = array(“Sam”=>1200, “Mike”=>1201, “Mac”=>1202);

Here, the individual values can be accessed as,

$empdetails[“Sam”] = “1200”;

9. What are the various PHP string functions?

PHP allows for many string operations. Some popular string functions are:

Function

Description

Example Usage

echo()

Output one or more string

echo"Welcome to hackr.io"

explode()

Break string into array

$mystr = “welcome to hackr.io”
explode(“ ”, $mystr)

will render [0] = “welcome” and so on

ltrim()

Removes extra characters or spaces from the left side of the string

ltrim($mystr, "…. hello")

parse_str()

Parses a query string into variables

parse_str("empId=1234&name=Sam");

str_replace()

Replaces specified characters of a string

str_replace("mysite","hackr.io","Welcome to mysite");

str_split()

Splits the string into character array

str_split("welcome")

str_word_count()

Word count of the string

str_word_count("my name is sam");

result = 4

strlen()

Calculates length of the string

strlen("welcome");

result = 7

strncmp()

Compare first few characters of a string

strncmp("welcome to mysite","welcome to hackr.io", 11);

result = 0 if the first 11 characters are same

For more string functions, refer to the PHP manual’s string functions.

10. What is the difference between require and include?

Both require and include are constructs and can be called without parentheses: include myfile.php

However, if the file that is to be included is not found, include will issue a warning, and the script will continue to run. Require will give a fatal error, and the script will stop then and there. If a file is critical to the script, then require should be used.

There are a plethora of PHP-based Content Management Systems in use today. Drupal, Joomla, and WordPress are the most popular among the bunch.

Intermediate PHP Questions

12. How do you upload files in PHP?

Firstly, PHP should allow file uploads; this can be done by making the directive file_uploads = On

You can then add the action method as 'post' with the encoding type as 'multipart/form-data.'

<formaction="myupload.php"method="post"enctype="multipart/form-data">

The myupload.php file contains code specific to the file type to be uploaded, like images or documents, and details like target path, size, and other parameters.

You can then write the HTML code to upload the file you want by specifying the input type as 'file.'

13. How do you create a database connection and query in PHP?

To create a database connection:

$connection = new mysqli($servername, $username, $password);

where $servername, $username, $password should be defined beforehand by the developer.

To check if the connection was successful:

if ($conn->connect_error) {

die("Connection error: " . $conn->connect_error);

}

Create database query:

$sql = "CREATE DATABASE PRODUCT";

if ($conn->query($sql) === TRUE) {

echo"Database successfully created";

} else {

echo"Error while creating database: " . $conn->error;

}

14. What are cookies? How do you create cookies in PHP?

Cookies store data about a user on the browser. It is used to identify a user and is embedded on the user's computer when they request a particular page. We can create cookies in PHP using the setcookie() function:

setcookie(name, value, expire, path, domain, secure, httponly);

Here name is mandatory, and all other parameters are optional.

Example:

setcookie(“instrument_selected”, “guitar”)

15. Explain the importance of the parser.

A PHP parser is a software that converts source code that the computer can understand. This means whatever set of instructions we give in the form of code is converted into a machine-readable format by the parser. You can parse PHP code with PHP using the token_get_all function.

16. Explain the constant() function and its purposes.

The constant function is used to retrieve the value of a constant. It accepts the name of the constant as the input:

constant(string $name)

The function returns a constant value, if available; otherwise, it returns null.

17. Can you provide an example of a PHP Web Application Architecture?

18. Define the use of .htaccess and php.ini files in PHP?

Both of them are used for making changes to the PHP settings.

  • .htaccess – A special file that can be used to change or manage the behavior of a website. Directing all users to one page and redirecting the domain’s page to https or www are two of the most important uses of the file. For .htaccess to work, PHP needs to be installed as an Apache module.
  • php.ini – This special file allows making changes to the default PHP settings. Either the default php.ini file can be edited, or a new file can be created with relevant additions and then saved as the php.ini file. For php.ini to work, PHP needs to run as CGI.

19. Draw a comparison between compile-time exception and the runtime exception. What are they called?

Checked exception is the exception that occurs at the compile time. As it is not possible to ignore this type of exception, it needs to be handled cautiously. An unchecked exception, on the other side, is the one that occurs during the runtime. If a checked exception is not handled, it becomes an unchecked exception.

20. Explain Path Traversal.

Path Traversal is a form of attack to read into the files of a web application. ‘../’ is known as dot-dot-sequences. It is a cross-platform symbol to go up in the directory. To operate the web application file, path traversal makes use of the dot-dot-slash sequences.

The attacker can disclose the content of the file attacked using the path traversal outside the root directory of a web server or application. It is usually done to gain access tokens, secret passwords, and other sensitive information stored in the files.

Path traversal is also known as directory traversal. It enables the attacker to exploit vulnerabilities present in the web file under attack.

21. Explain the difference between GET and POST requests.

Any PHP developer needs to have an adequate understanding of the HTTP protocol. The differences between GET and POST are an indispensable part of the HTTP protocol learning process. Here are the major differences between the two requests:

  • GET allows displaying the submitted data as part of the URL. This is not the case when using POST as during this time, the data is encoded in the request.
  • The maximum number of characters handled by GET is limited to 2048. No such restrictions are imposed on POST.
  • GET provides support for only ASCII data. POST, on the other hand, allows ASCII, binary data, as well as other forms of data.
  • Typically, GET is used for retrieving data while POST is used for inserting and updating data.

22. Explain the mail function and its syntax.

To directly send emails from a script or website, the mail() function is used in PHP. It has a total of 5 arguments. The general syntax of a mail function is:

mail (to, subject, message, headers, parameters);
  • To denotes the receiver of the email
  • Subject denotes the subject of the email
  • The message is the actual message that is to be sent in the mail (Each line is separated using /n, and the maximum character limit is 70.)
  • Headers denote additional information about the mail, such as CC and BCC (Optional)
  • Parameters denote to some additional parameter to be included in the send mail program (Optional)

Advanced PHP Questions

23. What is Memcache and Memcached? Is it possible to share a single instance of a Memcache between several PHP projects?

Memcached is an effective caching daemon designed specifically for decreasing database load in dynamic web applications. Memcache module offers a handy procedural and object-oriented interface to Memcached.

Memcache is a memory storage space, and it is possible to run Memcache on a single or several servers. Hence, it is possible to share a single instance of Memcache between multiple projects.

It is possible to configure a client to speak to a distinct set of instances. Therefore, running two different Memcache processes on the same host is also allowed. Despite running on the same host, both such processes stay independent, unless there is a partition of data.

24. How can you update Memcached when changes are made?

There are two ways of updating the Memcached when changes are made to the PHP code:

  1. Proactively cleaning the cache: This means clearing the cache when an insert or update is made
  2. Resetting the cache: Reset the values once the insert or update is made.

25. How is the comparison of objects done in PHP?

The operator ‘==’ is used for checking whether two objects are instanced using the same class and have the same attributes as well as equal values. To test whether two objects are referring to the same instance of the same class, the identity operator ‘===’ is used.

26. How is typecasting achieved in PHP?

The name of the output type needs to be specified in parentheses before the variable that is to be cast. Some examples are:

  • (array): casts to array
  • (bool), (boolean): casts to Boolean
  • (double), (float), (real): casts to float
  • (int), (integer): casts to integer
  • (object): casts to object
  • (string): casts to string

27. How would you connect to a MySQL database from a PHP script?

To connect to some MySQL database, the mysqli_connect() function is used. It is used in the following way:

<!--?php $database = mysqli_connect("HOST", "USER_NAME", "PASSWORD");

mysqli_select_db($database,"DATABASE_NAME"); ?-->

28. What are constructors and destructors? Provide an example.

Constructors and destructors in PHP are special types of functions, which are automatically called when a PHP class object is created and destroyed, respectively.

While a constructor is used to initialize the private variables of a class, a destructor frees the resources created or used by the class.

Here is a code example demonstrating the concept of constructors and destructors:

<?php

classConDeConExample {

private $name;

private $link;

publicfunction__construct($name) {

$this->name = $name;

 } # Constructor

publicfunctionsetLink(Foo $link){

$this->link = $link;

 }

publicfunction__destruct() {

echo'Destroying: ', $this->name, PHP_EOL;

 } # Destructor

}

?>

29. What are some common error types in PHP?

PHP supports three types of errors:

  • Notices: Errors that are non-critical. These occur during the script execution. Accessing an undefined variable is an instance of a notice.
  • Warnings: Errors that have a higher priority than notices. Like with notices, the execution of a script containing Warnings remains uninterrupted. An example of a notice includes a file that doesn’t exist.
  • Fatal Error: A termination in the script execution results as soon as such an error is encountered. Accessing a property of a non-existing object yields a fatal error.

30. What are the most important advantages of using PHP 7 over PHP 5?

  • Support for 64-bit integers: While PHP 7 comes with built-in support for native 64-bit integers and also for large files, PHP 5 doesn’t provide support for either of them.
  • Performance: PHP 7 performs far better than PHP 5. PHP 7 uses PHP-NG (NG stands for Next Generation), whereas PHP 5 relies on Zend II.
  • Return type: One of the most important downsides of PHP 5 is that it doesn’t allow for defining the return type of a function. This limitation is eliminated by PHP 7, which allows a developer to define the type of value returned by any function in the code.
  • Error handling: It is extremely difficult to manage fatal errors in PHP 5. PHP 7, on the other hand, comes with a new Exception Objects engine. It helps manage several major critical errors, which are now replaced with exceptions.
  • Anonymous class: These are executed only once to increase the execution time. This is not available in PHP 5.
  • Group use declaration: PHP 7 allows all the classes, constants, and functions to be imported from the same namespace to be grouped in a single-use statement. This is known as group use declaration. The feature is not available in PHP 5.
  • New operators: Several new operators are introduced to PHP 7, including ‘<=>’ and ‘??’ The former is known as the three-way comparison operator, and the latter is called the null coalescing operator.

31. What are the various ways of handling the result set of Mysql in PHP?

There are four ways of handling the result set of Mysql in PHP:

  • mysqli_fetch_array
  • mysqli_fetch_assoc
  • mysqli_fetch_object
  • mysqli_fetch_row

32. What are traits in PHP?

The traits mechanism allows for the creation of reusable code in PHP-like languages where there is no support for multiple inheritances. A trait can’t be instantiated on its own.

33. What is a session in PHP? Write a code example to demonstrate the removal of session data.

The simplest way to store data for individual users against a unique session ID is by using a PHP session. It is used for maintaining states on the server as well as sharing data across several pages. This needs to be done because HTTP is a stateless protocol.

Typically, session IDs are sent to the browser using session cookies. The ID is used for retrieving existing session data. If the session ID is not available on the server, then PHP creates a new session and then generates a new session ID.

Here is the program for demonstrating how session data is removed:

<?php

session_start();

$_SESSION['user_info'] = ['user_id' =>1,

'first_name' =>

'Hacker', 'last_name' =>

'.io', 'status' =>

'active'];

if (isset($_SESSION['user_info']))

{

echo"logged In";

}

unset($_SESSION['user_info']['first_name']);

session_destroy(); // Removal of entire session data

?>

34. What would you say is the best hashing method for passwords?

Rather than using the typical hashing algorithms, including md5, sha1, and sha256, it is preferable to use either crypt() or hash(). While crypt() provides native support for several hashing algorithms, hash() provides support for even more of them.

35. Why is it not possible for JavaScript and PHP to interact directly? Do you know any workarounds?

No direct interaction is possible between JS and PHP because, while the former is a client-side language, the latter is a server-side language. An indirect interaction between the two leading programming languages can happen using exchanging variables.

This exchange of variable is possible due to two reasons:

  1. PHP can generate JavaScript code meant to be executed by the browser.
  2. It is possible to pass a specific variable back to PHP via the URL. PHP always gets executed before JavaScript, so the JS variables must be passed via a form or the URL. To pass the variables, GET and POST are used. Similarly, to retrieve the passed variable, $_GET and $_POST are used.

36. Write code in PHP to calculate the total number of days between two dates?

<?Php

$date1 = ‘2019-01-11’; # Date 1

$date2 = ‘2019-01-09’; # Date 2

$days = (strtotime($date1)-strtotime($date2))/(60*60*24);

echo $days;

?>

Output:

1

There is a wide range of PHP frameworks available. Three of the most popular PHP frameworks are:

  • CodeIgniter: Simplistic and powerful, CodeIgniter is an incredibly lightweight PHP framework with a hassle-free installation process and minimalistic configuration requirements. The complete framework is a mere 2 MB and that includes the documentation. As it comes with many inbuilt modules for developing strong, reusable components, CodeIgniter is ideal for developing dynamic websites. The popular PHP framework also offers a smooth working experience on both dedicated as well as shared hosting platforms.
  • Laravel: Although not as old as some of the other popular PHP frameworks, Laravel is perhaps the most popular PHP framework. Launched in 2011, the immense popularity enjoyed by the PHP framework can be credited to its ability to offer additional speed and security for handling complex web applications. Laravel also eases the development process by reducing the complexity of repetitive tasks, including authentication, routing, sessions, and queuing.
  • Symfony: Used by PHP developers ever since its release back in 2005, Symfony is a popular PHP framework that has stood the test of time. An extensive PHP framework, Symfony, is the sole PHP framework that follows the standard of PHP and the web completely. Popular CMSs like Drupal, OroCRM, and PHPBB make use of Symfony components.

If you are interested in learning Codeigniter, Laravel or Symfony, then Hackr has programming community-recommended best tutorials and courses:

38. Draw a comparison between server-side and client-side programming languages.

Server-side programming languages are used for building programs that run on a server and generate the contents of a webpage. Examples of server-side programming languages include C++, Java, PHP, Python, and Ruby. A server-side programming language helps in:

  • Accessing and/or writing a file present on the server
  • Interacting with other servers
  • Processing user input
  • Querying and processing the database(s)
  • Structuring web applications

Contrary to server-side programming languages, client-side programming languages help in developing programs that run on the client machine, typically browser, and involves displaying output and/or additional processing, such as reading and writing cookies.

CSS, HTML, JavaScript, and VBScript are popular client-side programming languages. A client-side programming language allows:

  • Developing interactive web pages.
  • Interacting with temporary storage and/or local storage.
  • Making data and/or other requests to the server.
  • Offering an interface between the server and the end-user.

39. What are the differences between the echo and print statements in PHP?

There are two statements for getting output in PHP — echo and print. The distinctions between the two are:

  • Although used rarely, echo has the ability to take multiple parameters. The print statement, on the contrary, can accept only a single argument.
  • Echo has no return value whereas print has a return value of 1. Hence, the latter is the go-to option for use in expressions.
  • Generally, the echo statement is preferred over the print statement as it is slightly faster.

40. How do static websites differ from dynamic websites?

There are two types of websites: static and dynamic. The differences are:

  • The main advantage of a static website is flexibility, whereas the main advantage for a dynamic website comes in the form of a CMS.
  • Changes/Modification: Changes are made to the content of a static website only when the file is updated and published i.e., sent to the web server. Dynamic websites, on the other hand, contains “server-side” code that allows the server to generate unique content when the webpage is loaded.
  • Content: The content remains the same every time the page is reloaded for a static website. Contrarily, the content belonging to a dynamic website is updated regularly
  • Response: Static websites send the same response for every request whereas dynamic websites might generate different HTML for different requests.
  • Technologies: Only HTML is used for building static websites while dynamic websites are developed using several technologies, such as ASP.Net, JSP, Servlet, and PHP.

41. What is the use of the imagetypes() function?

The imagetypes() function gives the image format and types supported by the present version of the GD-PHP.

42. What is the difference between ‘passing the variable by value’ and ‘passing the variable by reference’ in PHP?

Passing the variable by value means that the value of the variable is directly passed to the called function. It then uses the value stored in the variable. Any changes made to the function doesn’t affect the source variable.

Passing the variable by reference means that the address of the variable where the value is stored is passed to the called function. It uses the value stored in the passed address. Any changes made to the function do affect the source variable.

43. What do you understand by typecasting and type juggling?

When a variable’s data type is converted explicitly by the user, it is known as typecasting. The PHP programming language doesn’t support explicit type definition in variable declaration. Hence, the data type of the variable is determined by the context in which the variable is used.

For example, if a string value is assigned to a $var variable, then it automatically gets converted to a string. Likewise, if an integer value is assigned to $var, then it becomes an integer. This is called type juggling.

44. How do you fetch data from a MySQL database using PHP?

To begin with, you need to first establish a connection with the MySQL database that you wish to use. For that, you can use the mysqli_connect() function.

Assume that the database that you need to access is stored on a server named localhost and has the name instanceDB. It also has user_name as the username and pass_word as the password.

For establishing a connection to the instanceDB, you need to use the following PHP code:

<?php

$servername = “localhost”;

$username = “user_name”;

$password = “pass_word”;

$dbname = “instanceDB”;

$conn = new mysqli($servername, $username, $password, $dbname);

if (!$conn) { // For checking connection to the database

die(“Connection failed: ” . mysqli_connect_error());

}

Next, you need to use the SELECT statement to fetch data from one or more tables. The general syntax is:

SELECT column_name from table_name

Suppose, we have a single table called instancetable with column_1, column_2, and column_3 in the instanceDB. To fetch data, we need to add the following PHP code:

$sql = “SELECT column_1, column_2, column_3 from instancetable”;

$result = $conn->query($sql);

45. How do you display text with PHP Script?

Either the echo statement or the print statement can be used for displaying text with a PHP script. Typically, the former is preferred over the latter because it is slightly faster.

46. What are parameterized functions?

Functions with parameters are known as PHP parameterized functions. It is possible to pass as many parameters as you’d like inside a function. Specified inside the parentheses after the function name, these all parameters act as variables inside the PHP parameterized function.

47. What is the difference between mysqli_connect() and mysqli_pconnect() functions?

Both mysqli_connect() and mysqli_pconnect() are functions used in PHP for connecting to a MySQL database. However, the latter ensures that a persistent connection is established with the database. It means that the connection doesn’t close at the end of a PHP script.

48. What is $_SESSION?

The $_SESSION[] is called an associative array in PHP. It is used for storing session variables that can be accessed during the entire lifetime of a session.

49. What is the difference between substr() and strstr() functions?

The substr() function returns a part of some string. It helps in splitting a string part-by-part in PHP. This function is typically available in all programming languages with almost the same syntax.

General syntax:

substr(string, start, length);

The strstr() function is used for searching a string within another string in PHP. Unlike the substr() function, strstr() is a case-sensitive function.

General syntax:

strstr(string, search, before_string);

50. What is the use of the $_REQUEST variable?

$_REQUEST is an associative array that, by default, contains the contents of the $_COOKIE, $_GET, $_POST superglobal variables.

Because the variables in the $_REQUEST array are provided to the PHP script via COOKIE, GET, and POST input mechanisms, it could be modified by the remote user. The variables and their order listed in the $_REQUEST array is defined in the PHP variables_order configuration directive.

51. What are the major differences between for and foreach loop?

The following are the differences between the for and for each loops:

  • The for-each loop is typically used for dynamic arrays.
  • The for loop has a counter and hence requires extra memory. The for-each loop has no counter, and hence there is no requirement for additional memory.
  • You need to determine the number of times the loop is to be executed when using the for a loop. However, you need not do so while using the for each loop.

52. Is it possible to submit a form with a dedicated button?

Yes, it is possible to submit a form with a dedicated button by using the document.form.submit() method. The code will be something like this:

<inputtype=buttonvalue=“SUBMIT”onClick=“document.form.submit()”>

53. Is it possible to extend a final defined class?

No, it isn’t possible to extend a final defined class. The final keyword prevents the class from extending. When used with a method, the final keyword prevents it from overriding.

54. Is it possible to extend the execution time of a PHP script?

Yes, it is possible to extend the execution time of a PHP script. We have the set_time_limit(int seconds) function for that. You need to specify the duration, in seconds, for which you wish to extend the execution time of a PHP script. The default time is 30 seconds.

Summary

That’s our list of PHP developer interview questions. Of course, there’s a lot more you can learn, but this is a good start. You could also look at our PHP Interview Questions with Solutions part 1 for more study material.

If you’d like to learn more, you should check out these PHP tutorials. Practice matters a lot as well! We also recommend a great book to prepare for the PHP Interview, which is Modern PHP: Modern PHP: New Features and Good Practices 1st Edition.

Good luck with your PHP interview!

People are also reading:

By Vijay Singh Khatri

With 5+ years of experience across various tech stacks such as C, C++, PHP, Python, SQL, Angular, and AWS, Vijay has a bachelor's degree in computer science and a specialty in SEO and helps a lot of ed-tech giants with their organic marketing. Also, he persists in gaining knowledge of content marketing and SEO tools. He has worked with various analytics tools for over eight years.

View all post by the author

Subscribe to our Newsletter for Articles, News, & Jobs.

I accept the Terms and Conditions.

Disclosure: Hackr.io is supported by its audience. When you purchase through links on our site, we may earn an affiliate commission.

In this article

Learn More

Please login to leave comments