PHP stands for PHP Hypertext Preprocessor and is a recursive acronym. It's a popular open-source programming language that's ideal for building dynamic web pages and mobile APIs.
In this blog, you can have a look at PHP interview questions that are helpful for 1 year, 2 years, 5 years of experience as a PHP developer. But before we begin, let’s have a quick look at the facts about PHP.
PHP is Originally Known as |
Personal Home Page |
PHP is designed by |
Rasmus Lerdorf |
PHP is written in |
C and C++ |
PHP first official launched |
June 1998 |
PHP is used for |
Creating dynamic websites, rest API's, Desktop Applications |
PHP Current Version |
7.4.12 |
The PHP interview questions and answers are divided into two categories:
So, let’s begin with the first section of PHP interview questions and answers.
Basic Level PHP questions
PHP Interview Questions for Freshers
1. What is PEAR in PHP?
PEAR is a framework and repository for PHP components that can be reused. PHP Extension and Application Repository (PEAR) is an acronym for PHP Extension and Application Repository. It's full of PHP code snippets and libraries of all kinds. It also has a command-line interface for automatically installing "packages."
2. What exactly is the distinction between static and dynamic websites?
Static Websites
Content on static websites cannot be altered after the script has been run. You can't edit anything on the site because it's already set up.
Dynamic Websites
The content of scripts on dynamic web pages can be altered at any time. Every time a user visits or reloads the page, the content is regenerated.
3. What are the common uses of PHP?
- It performs system functions, such as creating, opening, reading, writing, and closing files on a system.
- It can handle forms, which means it can gather data from files, save data to a file, send data via email, and return data to the user.
- PHP allows you to add, delete, and alter elements in your database.
- Cookies variables can be accessed and cookies can be set.
- You can restrict visitors' access to certain pages of your website and encrypt data using PHP.
4. What is the best way to run a PHP script from the command line?
Use the PHP Command Line Interface (CLI) to run a PHP script, and specify the script's filename as follows:
PHP script.php
5. Is PHP a case-sensitive language?
PHP is case-sensitive to some extent. The case of variable names is important, but not the case of function names. It will still work if you use lowercase for the function name and uppercase for the call. Although user-defined functions are not case-sensitive, the rest of the language is.
6. What does it mean to "escape to PHP"?
The PHP parsing engine requires a means to distinguish PHP code from other page components. 'Escape to PHP' is the mechanism used to do this. When you escape a string, you're reducing the amount of ambiguity in the quotes you're using.
7. What are the guidelines for naming variables in PHP?
When naming a PHP variable, the following principles must be followed:
- The first character in a variable name must be a letter or an underscore.
- You can use characters like +, –, percent, (,). &, etc. in a variable name, but you can't use characters like +, –, percent, (,). &, etc.
8. What distinguishes PHP variables from other types of variables?
The following are some of the most important characteristics of PHP variables:
- A leading dollar symbol ($) is used to denote all variables in PHP.
- A variable's value is the result of its most recent assignment.
- The = operator is used to assign variables, with the variable on the left and the expression to be evaluated on the right.
- Variables can be stated before the assignment, although they are not required.
- Variables in PHP don't have inherent types, which means they don't know if they'll be used to store a number or a string of characters before they're used.
- Variables with default values are those that are utilized before they are assigned.
9. What are the different types of PHP variables?
In PHP, there are eight data types that are utilized to create variables:
- Integers, such as 4195, are entire numbers without a decimal point.
- Floating-point numbers, such as 3.14159 or 49.1, are known as doubles.
- True or false are the only two possible values for Booleans.
- NULL is a unique type with only one value: NULL.
- Strings are character sequences, such as 'PHP supports string operations.'
- Arrays are collections of other values that are named and indexed.
- Objects are instances of programmer-defined classes that can bundle up both other types of values and class-specific functions.
- Resources are unique variables that store references to resources outside of PHP.
10. What are the rules for determining the "truth" of any value that isn't a Boolean value?
The following are the rules for determining the "truth" of any value that isn't already of the Boolean type:
- If the value is a number, it is true if it is precisely equal to zero and false if it is not.
- If the value is a string, it is false if the string is empty (has no characters), and true otherwise.
- Type NULL values are always false.
- If the value is an array, it is true if there are no other values in it, and false otherwise. A member variable that has been assigned a value is said to contain a value for an object.
- Doubles should not be used as Booleans.
11. What is NULL?
NULL is a unique data type that can only have one value. A variable with the data type NULL has no value associated with it. It can be assigned in the following way:
$var = NULL;
By tradition, the special constant NULL is capitalized, but it is case insensitive. As a result, you could also write it as:
$var = null;
A variable that has been assigned the NULL value consists of the following properties:
- In a Boolean context, it evaluates to FALSE.
- When tested using the IsSet() function, it returns FALSE.
12. In PHP, how do you define a constant?
You must use the define() function to define a constant, and you just merely mention its name to receive its value.
A constant can never be modified or undefined once it has been defined. There's no reason to use a $ as a constant. The name of a valid constant must begin with a letter or an underscore.
13. What does the constant() function do?
The constant() function returns the constant's value. This comes in handy when you need to access the value of a constant but don't know its name, such as when it's stored in a variable or returned by a function.
14. What's the difference between PHP variables and constants?
Constants
- A dollar ($) sign is not required before a constant.
- Only the define() function can be used to define constants.
- Without regard to variable scoping rules, constants can be defined and referenced everywhere.
- Constants can't be renamed or omitted.
Variables
The dollar ($) sign must be used when writing a variable.- Variables can be changed for each path separately.
- Functions in PHP can only create and access variables within their own scope by default.
- Simple assignments can be used to define variables.
15. Name a few PHP constants and explain what they do.
_LINE_ – This represents the file's current line number.
_FILE_ – It represents the file's complete path and filename. The name of the included file is returned if used inside an include.
_FUNCTION_ – This is the name of the function.
_CLASS_ – This function returns the name of the class as it was declared.
_METHOD_ – This is the name of the class method.
*PRO INTERVIEW TIP:
Practice for good non-verbal communication
- Stand straight
- Make eye contact while answering
- Make a firm handshake
- Feel confident
16. What are the benefits of using a break and continue statement?
Break – This statement terminates the for loop or switch statement and moves execution to the statement immediately after it.
Continue — This instructs the loop to skip the rest of its body and retest its state before repeating.
17. What are the two most common ways to start and finish the block of PHP code?
The following are the two most popular ways to begin and end a PHP block of code:
<?php [ --- PHP code---- ] ?>
<? [--- PHP code ---] ?>
18. What is the difference between PHP4 & PHP5?
PHP4
- The Constructor in PHP4 has the same name as the Class.
- Everything is done on a value basis.
- A class is not declared abstract in PHP4.
- In a class, there are no static methods or properties.
PHP5
- _construct and _destruct are the names of constructors and destructors, respectively ().
- References are used to pass all objects.
- A class can be declared abstract in PHP5.
- It lets a class have static Methods and Properties.
19. What do the terms "final class" and "final method" mean?
The final keyword in a method declaration implies that subclasses will not be able to override the method. It is not possible to subclass a class that has been declared final. This is especially handy when designing immutable classes, such as the String class. Only classes and methods can be declared final; properties cannot be declared final.
20. In PHP, how do you compare objects?
To see if two objects are instanced from the same class and have the same properties and values, we use the operator '=='. We may also use the identity operator '===' to see if two objects relate to the same instance of the same class.
21. What is the relationship between PHP and Javascript?
Because PHP is a server-side language and Javascript is a client-side language, they cannot interact directly. We may, however, exchange variables because PHP can generate Javascript code that is performed by the browser and specific variables can be passed back to PHP via the URL.
22. What is the relationship between PHP and HTML?
PHP scripts can generate HTML and transmit data between the two. Because PHP is a server-side language and HTML is a client-side language, PHP runs on the server and returns strings, arrays, and objects, which we then utilize to display the values in HTML.
23. Name a few of the most popular PHP frameworks.
The following are some of the most popular PHP frameworks:
- CakePHP
- CodeIgniter
- Yii 2
- Symfony
- Zend Framework
24. What are the different types of data types in PHP?
PHP support 9 primitive data types:
Scalar Types |
Compound Types |
Special Types |
|
|
|
25. What are constructors and destructors in PHP?
When a PHP class object is created or destroyed, special type functions named function Object() { [native code] } and destructor are automatically called. The function Object() { [native code] } is the more helpful of the two since it allows you to pass arguments along with a new object when creating it, which can then be used to set up variables on the object.
26. Explain require() and include() function.
The Require() function can also be used to transfer data from one PHP file to another. If there are any errors, require() function issues a warning and a fatal error, terminating the script's execution.
Include() is a PHP function that inserts data from one PHP file into another PHP file. If an error occurs, the include() function issues a warning but does not stop the script from running.
27. What's the difference between require() and require_once(), exactly?
require() includes and evaluates a single file, whereas requiring once() only does so if the file has never been included before. The require_once() statement can be used to include a PHP file in another when the called file needs to be included many times. So, if you want to include a file with a lot of functions, require_once() is the way to go.
28. Explain the syntax for the 'foreach' loop.
To loop through arrays, use the foreach expression. The current array element's value is assigned to $value in each pass, the array pointer is moved by one, and the next element is processed in the following pass.
Syntax-
foreach (array as value)
{
code to be executed;
}
29. In PHP, what are the different types of arrays?
In PHP, there are three types of arrays:
Indexed Array - An indexed array is one that has a numeric index. In a linear method, values are stored and accessed.
Associative Array - An associative array is an array with strings as an index. Rather than storing element values in a strict linear index sequence, this saves them in conjunction with key values.
Multidimensional Array - A multidimensional array is an array that contains one or more arrays. Multiple indices are used to access the values.
30. What's the difference between a single-quoted string and one that's double-quoted?
Single-quoted strings are regarded almost literally, whereas doubly quoted strings replace variables with their values and interpret certain character sequences differently.
*PRO INTERVIEW TIP:
Power dressing is very important.
- Wear formal dresses
- Black leather shoes (must be well-polished)
- Have a professional, simple, and nice haircut
- Cleanly Shaven
31. How do you concatenate two strings?
The dot (.) operator is used to join two string variables together.
32. Is it possible to provide a PHP script with an endless execution time?
The set time limit(0) directive at the start of a script sets the execution time to infinite to avoid the PHP error maximum execution time exceeded.' This can also be specified in the php.ini configuration file.
33. What is the difference between the PHP "echo" and "print"?
One or more strings are output by PHP echo. It's a feature of the language, not a function. As a result, there is no need to utilize parenthesis. If you wish to send more than one parameter to echo, you'll need to use parentheses. PHP, on the other hand, prints a string. It's a feature of the language, not a function. As a result, the argument list does not require the use of parentheses. In contrast to echo, it always returns 1.
Print can only output one string and always returns 1, but echo can emit one or more strings.
Because echo does not return a value, it is faster than print.
34. Name some of the functions in PHP.
Some of the functions in PHP include:
- ereg() – The ereg() function searches a string specified by string for a string specified by the pattern, returning true if the pattern is found, and false otherwise.
- ereg() – The ereg() function searches a string specified by string for a string specified by the pattern, returning true if the pattern is found, and false otherwise.
- split() – The split() function will divide a string into various elements, the boundaries of each element based on the occurrence of pattern in a string.
- preg_match() – The preg_match() function searches a string for a pattern, returning true if a pattern exists, and false otherwise.
- preg_split() – The preg_split() function operates exactly like split(), except that regular expressions are accepted as input parameters for pattern.
35. What do the initials of PHP stand for?
PHP means PHP: Hypertext Preprocessor.
36. What is the actually used PHP version?
Version 7.1 or 7.2 is the recommended version of PHP.
37. How can we display the output directly to the browser?
To be able to display the output directly to the browser, we have to use the special tags <?= and ?>.
38. Is PHP capable of multiple inheritances?
PHP only supports single inheritance, which means that a class can be extended by using the term 'extended' from only one other class.
39. What is the relationship between PHP and HTML?
It is possible to generate HTML through PHP scripts, and it is possible to pass pieces of information from HTML to PHP.
40. What type of operation is needed when passing values through a form or an URL?
If we would like to pass values through a form or an URL, then we need to encode and to decode them using htmlspecialchars() and urlencode().
41. What is required to use the image function?
To run image functions, you'll need the GD library.
42. What is the purpose of the imagetypes() function?
imagetypes() returns the supported image formats and types in the current version of GD-PHP.
43. What are the functions to be used to get the image’s properties (size, width, and height)?
The functions are getimagesize() for size, imagesx() for width and imagesy() for height.
44. How can we display information of a variable and readable by a human with PHP?
To be able to display a human-readable result we use print_r().
45. How can we check the value of a given variable is a number?
It is possible to use the dedicated function, is_numeric() to check whether it is a number or not.
*PRO INTERVIEW TIP:
Be a good listener.
46. How can we check if the value of a given variable is alphanumeric?
It is possible to use the dedicated function, ctype_alnum to check whether it is an alphanumeric value or not.
47. What does the unlink() function mean?
The unlink() function is dedicated to file system handling. It simply deletes the file given as an entry.
48. How can we automatically escape incoming data?
We have to enable the Magic quotes entry in the configuration file of PHP.
49. Is it possible to remove the HTML tags from the data?
The strip_tags() function enables us to clean a string from the HTML tags.
50. How is it possible to return a value from a function?
A function returns a value using the instruction ‘return $value;’.
Looking to hire a PHP developer? Explore this comprehensive guide! Discover the essential expertise and qualifications to consider when hiring job-fit PHP developer.
iMocha offers coding assessments for over 35 languages, so why struggle hiring for niche roles! |
Advanced level PHP Interview Questions
PHP Interview Questions for Experienced
51. Write a query for the following question
The table tbl_sites contains the following data: --------------------------------------- Userid Sitename country ---------------------------------------
1 Suresh babu Indian
2 PHP programmer Andhra
3 PHP.net USA
4 PHPtalk.com Germany
5 MySQL.com USA
6 Suresh babu Canada
7 PHPbuddy.com Pakistan
8 PHPtalk.com Austria
9 PHPfreaks.com South Africa
10 PHPsupport.net Russia
11 Suresh babu Australia
12 Suresh babu Nepal
13 PHPtalk.com Italy
52. Write a select query that will be displayed the duplicated site name and how many times it is duplicated?
SELECT Sitename, COUNT(*) AS NumOccurrences FROM tbl_sites GROUP BY Sitename HAVING COUNT(*) > 1
53. What are the advantages and disadvantages of using session and cookies in PHP?
A session is a server-stored global variable. A unique id is assigned to each session and is used to retrieve saved values. When opposed to cookies, sessions have the ability to store a lot of data. When the browser is closed, the session values are automatically removed.
The example below demonstrates how to create a cookie in PHP.
<?php $cookie_value = "edureka"; setcookie("edureka", $cookie_value, time()+3600, "/your_usename/", "edureka.co", 1, 1); if (isset($_COOKIE['cookie'])) echo $_COOKIE["edureka"]; ?>
The example below demonstrates how to start a session in PHP.
<?php session_start(); if( isset( $_SESSION['counter'] ) ) { $_SESSION['counter'] += 1; }else { $_SESSION['counter'] = 1; } $msg = "You have visited this page". $_SESSION['counter']; $msg .= "in this session."; ?>
54. What is the difference between overloading and overriding in PHP?
Overloading is the process of creating functions with similar signatures but differing parameters. Overriding is only relevant to derived classes when the parent class defines a method that the derived class wants to override. Only the magic method __call can be used to overload methods in PHP.
55. In PHP, how do you tell the difference between $message and $$message?
Both of them are variables. $message, on the other hand, is a named variable. $message stores the name of a variable called $$message. $$message, for example, is the same as $var if $message contains "var."
56. How do we use PHP and MySQL to create a database?
The following are the fundamental procedures for creating a MySQL database with PHP:
- From your PHP script, establish a connection to the MySQL server.
- If the connection is successful, construct a database using SQL and save it in a string variable.
- Carry out the query.
57. What is the difference between the GET and POST methods?
The encoded user information attached to the page request is sent using the GET method. The? character separates the page from the encoded content.
For instance —
<a href="http://www.test.com/index.htm?name1=value1&name2=value2">http://www.test.com/index.htm?name1=value1&name2=value2</a>
The POST method uses HTTP headers to send data. The data is encoded as specified for the GET method and stored in the QUERY STRING header.
58. What is the purpose of the callback function in PHP?
PHP callbacks are functions that PHP can use to call them dynamically. Native functions such as array map, usort, preg replace callback, and others use them. A callback function is a function that you write and then provide as a parameter to another function. Once the receiving function has access to your callback function, it can use it whenever it wants.
59. What is a lambda function?
A lambda function is an anonymous PHP function that can be stored in a variable and passed as an argument to other functions or methods. A closure is a lambda function that is aware of its surrounding context.
60. What are PHP Magic Functions/Methods?
All functions in PHP that begin with the letter are magical functions/methods. These methods, which have a two underscore prefix (__), are interceptors that are called automatically when particular circumstances are satisfied. PHP has a lot of 'magic' ways that let you perform some very cool object-oriented programming tricks.
*PRO INTERVIEW TIP:
Never speak unnecessarily.
- Speak less but to the point
- Don't ramble (You must be well prepared to avoid this situation)
- Focus on your strong skills
- Speak appropriate sentences
61. How can you encrypt passwords using PHP?
To construct one-way encryption, use the crypt () function. One input string and one optional argument are required. crypt (input string, salt) is the function's definition, where input string is the string to be encrypted and salt is an optional parameter. Encryption in PHP is done with DES.
62. How do you connect to a URL?
PHP comes with a library named cURL, which may already be installed by default. cURL stands for client URL, and it allows you to connect to a URL and retrieve information from it, such as the page's HTML text, HTTP headers, and associated data.
63. What is Type Hinting?
In a function declaration, type hinting is used to define the intended data type of an argument. PHP will check whether the parameters are of the required type when you call the function. If you don't, the run-time will throw an error and your program will be terminated.
64. What's the difference between a compile-time and a runtime exception?
A checked exception is one that happens during the compilation process. This is an exception that cannot be overlooked and must be treated with caution. If you use the FileReader class to read data from a file and the file supplied in the class function Object() { [native code] } does not exist, you will get a FileNotFoundException, which you must handle. You'll need to write the code in a try-catch block and then handle the exception. Unchecked exception, on the other hand, refers to an exception that happens at runtime.
65. What is the most practical hashing algorithm for hashing passwords?
Instead of utilizing the typical hashing methods such as md5, sha1, or sha256, which are envisioned to be quick, it is recommended to use crypt(), which natively supports many hashing algorithms, or the function hash(), which offers more variants than crypt(). As a result, using these techniques to hash passwords can expose them to attack.
66. Which cryptographic extension allows you to create and verify digital signatures?
The PHP-OpenSSL extension supports a variety of cryptographic activities, including digital signature generation and verification.
67. How is it possible to cast types in PHP?
The name of the output type has to be specified 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
* (string) – cast to string
* (array) – cast to an array
* (object) – cast to object
68. In PHP, how does the ternary conditional operator work?
It consists of three expressions: a condition and two operands that specify which instruction should be executed when the provided condition is true or false, as follows:
Expression_1?Expression_2 : Expression_3;
69. What is the purpose of the function func_num_args()?
The number of parameters provided into a function is returned by the method func_num_args().
70. What is the value of $$var2 if the variable $var1 is set to 10 and the variable $var2 is set to the character var1?
The value 10 is contained in $$var2.
71. What does accessing a class via:: means?
:: is used to access static methods that do not require object initialization.
72. In PHP, objects are passed by value or by reference?
In PHP, objects are passed by reference.
73. Are Parent constructors called implicitly inside a class constructor?
No, a parent constructor has to be called explicitly as follows:
parent::constructor($value)
74. What’s the difference between __sleep and __wakeup?
__sleep returns the array of all the variables that need to be saved, while __wakeup retrieves them.
75. What is the meaning of a Persistent Cookie?
A persistent cookie is permanently stored in a cookie file on the browser’s computer. By default, cookies are temporary and are erased if we close the browser.
*PRO INTERVIEW TIP:
Advised to talk in a professional manner.
76. When do sessions end?
Sessions automatically end when the PHP script finishes executing but can be manually ended using the session_write_close().
77. What makes session unregister() and session unset() different?
The session unregister() function frees all session variables while the session unset() function unregisters a global variable from the current session.
78. What does $GLOBALS mean?
$GLOBALS is an associative array including references to all variables which are currently defined in the global scope of the script.
79. What does the term $_SERVER imply?
The array $_SERVER contains information generated by the webserver, such as paths, headers, and script locations.
80. What does the term $_FILES imply?
$_FILES is an associative array of things delivered over the HTTP POST method to the current script.
81. Where does the distinction between $_FILES['userfile']['name'] and $_FILES['userfile']['tmp name'] come from?
$_FILES[‘user file]
The original name of the file on the client system is represented by ['name'].
The temporary filename of the file kept on the server is represented by $_FILES['user file]['tmp name'].
82. What is MVC?
MVC is an application in PHP which separates the application data and model from the view.
The full form of MVC is Model, View & Controller. The controller is used to interact between the models and views.
Example: Laravel, Yii, etc
83. What is namespace in PHP?
A namespace allows us to use the same function or class name in different parts of the same program without causing a name collision.
84. What is the difference between the ‘BITWISE AND’ operator and the ‘LOGICAL AND’ operator?
$a and $b: TRUE if both $a and $b are TRUE.
$a & $b: Bits that are set in both $a and $b are set.
85. What is the goto statement useful for?
The goto statement can be placed to enable jumping inside the PHP program. The target is pointed by a label followed by a colon, and the instruction is specified as a goto statement followed by the desired target label.
86. What does the expression Exception::__toString mean?
Exception::__toString gives the String representation of the exception.
87. How is it possible to parse a configuration file?
The function parse_ini_file() enables us to load in the ini file specified in the filename and returns the settings in it in an associative array.
88. How can we determine whether a variable is set?
The boolean function isset determines if a variable is set and is not NULL.
89. What is the difference between the functions strstr() and stristr()?
The string function strstr(string allString, string occ) returns part of allString from the first occurrence of occ to the end of allString. This function is case-sensitive. stristr() is identical to strstr() except that it is case insensitive.
90. What is the difference between ereg_replace() and eregi_replace()?
The function eregi_replace() is identical to the function ereg_replace() except that it ignores case distinction when matching alphabetic characters.
91. Is it possible to protect special characters in a query string?
Yes, we use the urlencode() function to be able to protect special characters.
92. What are the three classes of errors that can occur in PHP?
The three basic classes of errors are notices (non-critical), warnings (serious errors), and fatal errors (critical errors).
93. What is the difference between characters \034 and \x34?
\034 is octal 34 and \x34 is hex 34.
94. How can we pass the variable through the navigation between the pages?
It is possible to pass the variables between the PHP pages using sessions, cookies, or hidden form fields.
95. Is it possible to extend the execution time of a PHP script?
The use of the set_time_limit(int seconds) enables us to extend the execution time of a PHP script. The default limit is 30 seconds.
96. Is it possible to destroy a cookie?
Yes, it is possible by setting the cookie with a past expiration time.
97. What is the default session time in PHP?
The default session time in PHP is until the closing of the browser
98. Is it possible to use the COM component in PHP?
Yes, it’s possible to integrate (Distributed) Component Object Model components ((D)COM) in PHP scripts which is provided as a framework.
99. Explain whether a single Memcache instance may be shared between numerous PHP projects.
Yes, a single instance of Memcache can be shared across numerous projects. Memcache is a memory cache that can be installed on one or more servers. You can also set your client to communicate with a certain set of instances. So, on the same host, you can run two distinct Memcache processes that are fully independent. Unless you've partitioned your data, you'll need to know which instance to obtain the data from or which instance to put it into.
100. Explain how you can update Memcached when you make changes to PHP?
When PHP changes you can update Memcached by -
- Clearing the Cache proactively: Clearing the cache when an insert or update is made
- Resetting the Cache: It is similar to the first method but rather than just deleting the keys and waiting for the next request for the data to refresh the cache, reset the values after the insert or update.
101. How can we define a variable accessible in functions of a PHP script?
This feature is possible using the global keyword.
102. How is it possible to return a value from a function?
A function returns a value using the instruction ‘return $value;’.
Interested in discovering the essential roles and responsibilities of a senior PHP developer? Check out this blog to explore the primary operational domains of senior PHP developers excel.
Conclusion
With this, we have come to the end of the PHP interview questions blog. I hope these PHP Interview Questions and Answers will help you conduct and face interviews. In case you have attended any PHP interviews in the recent past, do share those interview questions with us at support@imocha.io we’ll answer them.
If you wish to explore your PHP skills, try iMocha's software engineer skills assessment and explore skills.