PHP Interview Questions

Here are the top 50 commonly asked questions in PHP interviews. Whether you’re just starting your preparation or need a quick refresher, these questions and answers will help you tackle your interview with confidence.

Basic PHP Interview Questions with Answers

1. What is PHP?

PHP stands for Hypertext Preprocessor. It’s a server-side scripting language used for web development.

2. What are the features of PHP?

PHP features include simplicity, flexibility, security, efficiency, and cross-platform compatibility.

3. What are the differences between PHP and HTML?

PHP is a server-side scripting language, while HTML is a markup language. PHP can generate dynamic content, interact with databases, and handle forms, while HTML is used for creating the structure of web pages.

4. What is the syntax for commenting in PHP?

Single-line comments start with //, and multi-line comments are enclosed between /* and */.

5. How do you declare a variable in PHP?

Variables in PHP start with the dollar sign ($), followed by the variable name. For example: $variable_name = value;

6. What are the different data types supported by PHP?

PHP supports data types such as integers, floats, strings, booleans, arrays, and objects.

advertisement
advertisement

7. What is the use of the ‘echo’ statement in PHP?

The ‘echo’ statement is used to output data to the browser. It can be used to display HTML, variables, or any other text.

8. What is the difference between ‘==’, ‘===’, ‘!=’, and ‘!==’ operators in PHP?

‘==’ checks for equality of value, while ‘===’ checks for equality of value and data type. ‘!=’ checks for inequality of value, while ‘!==’ checks for inequality of value and data type.

9. What are PHP sessions, and how are they used?

PHP sessions allow you to store user data on the server between page requests. They are used to maintain stateful information across multiple pages of a website.

10. How can you upload files in PHP?

You can use the $_FILES superglobal array along with the move_uploaded_file() function to upload files in PHP.

11. What is the purpose of the ‘foreach’ loop in PHP?

The ‘foreach‘ loop is used to iterate over arrays in PHP. It allows you to loop through each key/value pair in an array.

12. What are namespaces in PHP, and how are they used?

Namespaces are used to avoid naming conflicts between classes, functions, and constants. They allow you to organize your code into logical groups and improve code readability and maintainability. You can define namespaces using the ‘namespace’ keyword.

13. What is the purpose of the ‘include’ and ‘require’ statements in PHP?

Include‘ and ‘require‘ are used to include external files in PHP scripts. ‘Include’ will only produce a warning if the file is not found, while ‘require’ will produce a fatal error.

14. What is the difference between ‘echo’ and ‘print’ in PHP?

Both ‘echo‘ and ‘print‘ are used to output data, but ‘echo’ can output multiple values separated by commas, while ‘print’ can only output one value and always returns 1.

15. How can you handle errors and exceptions in PHP?

You can use the ‘try’, ‘catch’, and ‘finally’ blocks to handle exceptions in PHP. You can also use the error_reporting() function to set error reporting level and display_errors directive in php.ini to display errors.

advertisement

16. What is the ternary operator in PHP?

The ternary operator (? :) is a shorthand for an if-else statement. It takes three operands: a condition followed by a question mark (?), an expression to be evaluated if the condition is true, and another expression to be evaluated if the condition is false. For example:

$result = ($a > $b) ? 'A is greater' : 'B is greater';

17. What is object-oriented programming (OOP) in PHP?

Object-oriented programming is a programming paradigm based on the concept of “objects”, which can contain data in the form of fields (attributes or properties), and code in the form of procedures (methods). OOP in PHP involves defining classes, creating objects, and using inheritance, encapsulation, and polymorphism.

18. How do you define and call a function in PHP?

Functions in PHP are defined using the ‘function’ keyword followed by the function name and parameters. They can be called by simply using the function name followed by parentheses. Example:

function greet($name) {
    echo "Hello, $name!";
}
greet("John");

19. How do you define a constant in PHP?

Constants in PHP are defined using the define() function. Once defined, their value cannot be changed during the script execution. Example: define(“PI”, 3.14);

advertisement

20. What is the purpose of the ‘return’ statement in PHP?

The ‘return’ statement is used to end the execution of a function and return a value to the calling code. It can be used to pass back a value computed by the function.

Intermediate PHP Interview Questions with Answers

21. What are logical operators in PHP?

Logical operators in PHP are used to perform logical operations on two or more conditions. The main logical operators are:

  • AND (&&): Returns true if both conditions are true.
  • OR (||): Returns true if at least one of the conditions is true.
  • NOT (!): Returns the opposite of the condition’s result.

22. What is the purpose of the define() function in PHP?

The define() function in PHP is used to define constants. Constants are identifiers (names) for simple values that do not change throughout the script’s execution. Constants are case-sensitive by default and can be accessed globally.

23. How do you fetch data from a MySQL database in PHP?

To fetch data from a MySQL database in PHP, you first establish a connection using mysqli or PDO, then execute a SELECT query using mysqli_query() or PDO::query() method. After that, you can fetch rows from the result set using functions like mysqli_fetch_assoc(), mysqli_fetch_array(), or PDOStatement::fetch().

24. Explain the usage of $_SESSION superglobal in PHP.

The $_SESSION superglobal in PHP is used to store and access session variables. These variables can be accessed across multiple pages during a user’s session. They are typically used to maintain user-specific data, such as login status, user preferences, or shopping cart items.

25. How do you destroy a session in PHP?

To destroy a session in PHP, you can use the session_destroy() function. This function terminates the current session and deletes all session data associated with the session. It is commonly used when a user logs out of a website or when a session timeout occurs.

26. How do you log errors in PHP?

Errors in PHP can be logged using the error_log() function. You can specify the error message, error type, and log destination (e.g., a file, system log, or email). Additionally, you can configure PHP error logging settings in the php.ini file to control error reporting levels and log destinations.

27. How can you throw a custom exception in PHP?

To throw a custom exception in PHP, you can use the throw keyword followed by a new instance of the Exception class (or a subclass of Exception). You can provide a custom error message as an argument to the Exception constructor to describe the reason for the exception.

28. Explain the difference between call by value and call by reference in PHP functions.

In call by value, a copy of the variable’s value is passed to the function, so changes made to the parameter inside the function do not affect the original variable outside the function. In call by reference, a reference to the variable’s memory address is passed to the function, allowing changes made to the parameter inside the function to affect the original variable outside the function.

29. Explain the Singleton design pattern in PHP.

The Singleton design pattern ensures that a class has only one instance and provides a global point of access to that instance. It involves defining a private constructor to prevent direct instantiation of the class and providing a static method to return the single instance of the class, creating it if it doesn’t exist.

30. How do you execute a SQL query in PHP?

To execute a SQL query in PHP, you first establish a connection to the database using mysqli or PDO. Then, you prepare the SQL query as a string and execute it using mysqli_query() or PDOStatement::execute() method, depending on the database extension used.

31. How do you concatenate strings in PHP?

In PHP, strings can be concatenated using the ‘.’ (dot) operator. For example:

$str1 = "Hello";
$str2 = "World";
$result = $str1 . ", " . $str2; // Result: "Hello, World"

32. How do you define a constructor and destructor in PHP?

In PHP, a constructor is a special method with the same name as the class, which is automatically called when an object of the class is created. It is used to initialize object properties or perform any necessary setup tasks. A destructor is a special method named __destruct() which is called automatically when an object is destroyed or goes out of scope. It is used to release resources or perform cleanup tasks.

33. Explain the usage of array_merge() function in PHP.

The array_merge() function in PHP is used to merge two or more arrays into a single array. It takes multiple array arguments and returns a new array containing the elements of all the arrays. If two or more arrays have the same string keys, the later value will overwrite the previous one.

34. How do you start and end a PHP script?

A PHP script is started with the opening <?php tag and ended with the closing ?> tag. Everything between these tags is interpreted as PHP code, and anything outside these tags is treated as HTML or text. It’s also worth noting that for files containing only PHP code, it’s recommended to omit the closing ?> tag to avoid unintended whitespace or output after the closing tag, which can cause issues in some cases.

35. What is the purpose of the preg_match() function in PHP?

The preg_match() function in PHP is used to perform a regular expression match on a string. It searches the given string for a pattern specified by a regular expression and returns true if the pattern is found, and false otherwise. Additionally, if matches are found, preg_match() can populate an array with the matched substrings.

36. What is the difference between sessions and cookies in PHP?

Sessions are server-side mechanisms for storing and managing user-specific data across multiple pages during a user’s visit to a website, whereas cookies are small pieces of data sent from a website and stored on the client’s browser. Sessions store data on the server and are identified by a session ID sent to the client’s browser, while cookies store data locally on the client’s browser.

37. How can you remove duplicate values from an array in PHP?

To remove duplicate values from an array in PHP, you can use the array_unique() function. This function takes an array as input and returns a new array with duplicate values removed, while preserving the order of the original array’s elements.

38. Explain the purpose of the null coalescing operator (??) in PHP.

The null coalescing operator (??) in PHP is used to provide a default value for a variable if the variable is null or undefined. It allows for concise and readable code when dealing with potentially null variables, avoiding the need for verbose ternary operators or checks. If the variable on the left side of the operator is not null, its value is returned; otherwise, the value on the right side of the operator is returned.

39. What is the purpose of the isset() function in PHP?

The isset() function in PHP is used to determine whether a variable is set and is not NULL. It returns true if the variable exists and has a non-null value, and false otherwise. isset() is commonly used to check if form inputs or variables are set before accessing or using them in PHP scripts.

40. What is the purpose of the array_unique() function in PHP?

The array_unique() function in PHP is used to remove duplicate values from an array. It returns a new array containing only the unique values from the original array, while preserving the order of the elements.

PHP Programming Interview Questions with Answers

41. What will be the output of the following PHP program?

<?php
$a = 5;
$b = 10;
echo $a.$b;
?>

Answer: 510

Explanation:

  • The variables $a and $b are assigned the integer values 5 and 10, respectively.
  • When concatenating variables in PHP using the ‘.’ (dot) operator, they are treated as strings regardless of their original types.
  • Therefore, the expression $a.$b concatenates the string representations of $a and $b, resulting in “510“.

42. What will be the output of the following PHP program?

<?php
echo str_repeat("Hello", -1);
?>

Answer: Output will be nothing (an empty string).

Explanation: The output will be nothing, as providing a negative value (-1) to the str_repeat() function results in no output.

43. What will be the output of the following PHP program?

<?php
$variable = 0;
$result = ++$variable + $variable++;
echo $result;
?>

Answer: 1

Explanation: The pre-increment operator ++$variable increments $variable before its value is used in the addition, resulting in 1. The post-increment operator $variable++ increments $variable after its value is used in the addition, but for this operation, its value remains 1. So, the expression evaluates to 1 + 1 = 2. However, when echoed, $result reflects the value of $variable before the post-increment operation, which is 1. Hence, the output is 1.

44. What will be the output of the following PHP program?

<?php
$array = [1, 2, 3];
foreach ($array as &$value) 
{
    $value *= 2;
}
print_r($array);
?>

Answer:

Array
(
    [0] => 2
    [1] => 4
    [2] => 6
)

Explanation:

  • The code initializes an array $array containing elements [1, 2, 3].
  • The foreach loop iterates over each element of the array by reference (&$value).
  • Inside the loop, each element $value is multiplied by 2.
  • After the loop completes, the array $array is printed using the print_r() function, which displays the modified elements [2, 4, 6].

45. What will be the output of the following PHP program?

<?php
function test() {
    static $count = 0;
    $count++;
    echo $count;
}
test();
test();
?>

Answer: 12

Explanation: The function test() increments a static variable $count each time it’s called and then echoes its value. So, on the first call, it outputs 1, and on the second call, it outputs 2.

46. What will be the output of the following PHP program?

<?php
$number = 10;
if ($number > 5) 
{
    echo "Greater than 5";
} 
else 
{
    echo "Less than or equal to 5";
}
?>

Answer: Greater than 5

Explanation:

  • The variable $number is assigned the value 10.
  • The if statement checks if $number is greater than 5.
  • Since 10 is indeed greater than 5, the condition evaluates to true.
  • Therefore, the code block inside the if statement, echo “Greater than 5”, is executed, resulting in the output Greater than 5.

47. What will be the output of the following PHP program?

<?php
$string = "hello";
echo strtoupper($string[0]);
?>

Answer: H

Explanation:

  • The variable $string is assigned the string “hello”.
  • $string[0] accesses the first character of the string, which is “h”.
  • The strtoupper() function converts the string to uppercase, resulting in “H”.
  • Therefore, echo strtoupper($string[0]); outputs “H”.

48. What will be the output of the following PHP program?

<?php
$a = 10;
$b = "10";
echo $a == $b ? "true" : "false";
?>

Answer: true

Explanation: The loose comparison == converts the string “10” to an integer and compares it with the integer 10, resulting in equality. Hence, the output is true.

49. What will be the output of the following PHP program?

<?php
echo strlen(trim("  Hello World!  "));
?>

Answer: 11

Explanation: The trim() function removes leading and trailing whitespace from the string ” Hello World! “, resulting in “Hello World!”. The strlen() function then calculates the length of this trimmed string, which is 11 characters.

50. What will be the output of the following PHP program?

<?php
$a = 5;
echo ++$a + $a++;
?>

Answer: 12

Explanation: The pre-increment operator ++$a increments $a to 6 before its value is used in the addition operation. The post-increment operator $a++ increments $a after its value is used in the addition operation, but for this operation, its value remains 5. So, the expression becomes 6 + 5, resulting in 11. However, when echoed, the value reflects the post-increment value of $a, which is 6. Hence, the output is 12.

If you find any mistake above, kindly email to [email protected]

advertisement
advertisement
Subscribe to our Newsletters (Subject-wise). Participate in the Sanfoundry Certification contest to get free Certificate of Merit. Join our social networks below and stay updated with latest contests, videos, internships and jobs!

Youtube | Telegram | LinkedIn | Instagram | Facebook | Twitter | Pinterest
Manish Bhojasia - Founder & CTO at Sanfoundry
Manish Bhojasia, a technology veteran with 20+ years @ Cisco & Wipro, is Founder and CTO at Sanfoundry. He lives in Bangalore, and focuses on development of Linux Kernel, SAN Technologies, Advanced C, Data Structures & Alogrithms. Stay connected with him at LinkedIn.

Subscribe to his free Masterclasses at Youtube & discussions at Telegram SanfoundryClasses.