Jese Leos


PHP Top 100 interview questions

1. What is PHP?

PHP is a server-side scripting language designed for web development but also used as a general-purpose programming language. It stands for Hypertext Preprocessor.

 

2. What are the differences between PHP variables and constants?

Variables in PHP hold data that can change during the execution of a script, while constants are identifiers whose values cannot be changed during the execution of the script.

// Variables
                        $name = "John";
                        $age = 30;
                        // Constants
                        define("PI", 3.14);
                        const WEBSITE_NAME = "Example.com";

 

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

PHP supports various data types including integers, floats (floating-point numbers), strings, booleans, arrays, objects, NULL, and resources.

// Different data types
                        $integerVar = 10;
                        $floatVar = 3.14;
                        $stringVar = "Hello, world!";
                        $boolVar = true;
                        $arrayVar = array(1, 2, 3);
                        $objectVar = new stdClass();
                        $nullVar = null;
                        $resourceVar = fopen("example.txt", "r");

 

4. What is the difference between == and === operators in PHP?

  •  == operator checks if the values of two operands are equal, whereas the
  •  === operator checks if the values and data types of two operands are equal.
// == vs ===
                        $num1 = 10;
                        $num2 = "10";
                        if ($num1 == $num2) {
                            echo "Equal in value";
                        }
                        if ($num1 === $num2) {
                            echo "Equal in value and type";
                        }

 

5. Explain the difference between echo and print in PHP.

echo can output one or more strings, and it is slightly faster than print. print is a language construct and always returns 1, while echo is a language construct as well but doesn't return any value.

 // echo vs print
                        echo "Hello, world!";
                        print "Hello, world!";

6. What are the PHP superglobal arrays?

PHP superglobal arrays are predefined variables that are always available in all scopes. Some of the superglobal arrays in PHP include

  •  $_GET
  •  $_POST
  •  $_SERVER
  •  $_SESSION
  • $_COOKIE
  •  $_FILES
  • $_REQUEST

 

7. How can you prevent SQL injection in PHP?

To prevent SQL injection in PHP, you can use prepared statements and parameterized queries with PDO (PHP Data Objects) or MySQLi extension. These methods help sanitize user input and prevent malicious SQL queries from being executed.

$pdo = new PDO('mysql:host=localhost;dbname=mydb', 'username', 'password');
                        $stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
                        $stmt->execute(['username' => $username]);
                        $user = $stmt->fetch();

 

8. What is a session in PHP?

A session in PHP is a way to preserve data across subsequent HTTP requests. It allows information to be stored on the server for later use, typically used to keep track of user login sessions and store user-specific data. Sessions are often managed using session cookies.

// Starting a session
                        session_start();
                        // Setting session variables
                        $_SESSION['user_id'] = 123;
                        $_SESSION['username'] = 'john_doe';
                        // Accessing session variables
                        echo "Welcome, ".$_SESSION['username'];

 

9. Explain the difference between GET and POST methods in PHP.

  • GET: Sends data via the URL as key-value pairs, visible to the user, suitable for non-sensitive information. 
  • POST: Sends data in the HTTP header, not visible to the user, suitable for sensitive information.
// GET method
                        $value = $_GET['key'];
                        // POST method
                        $value = $_POST['key'];

 

10. What is the use of the function htmlentities() in PHP?

htmlentities(): Converts characters with special meaning in HTML to their corresponding HTML entities to prevent XSS attacks.

$safe_data = htmlentities($unsafe_data);

 

11. What is the difference between include() and require() functions in PHP?

require(): Produces a fatal error if the specified file is not found, while include(): only produces a warning and continues script execution.

// require() example
                        require('file.php');
                        // include() example
                        include('file.php');

 

12. How can you get the IP address of the client in PHP?

You can use: $_SERVER['REMOTE_ADDR'] to get the IP address of the client.

$client_ip = $_SERVER['REMOTE_ADDR'];

 

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

header(): Used to send raw HTTP headers to the client, often used for redirection or setting cookies.

header('Location: http://www.example.com');

 

14. Explain the purpose of the explode() function in PHP.

explode(): Splits a string into an array of substrings based on a specified delimiter, useful for parsing delimited data.

$array = explode(",", $string);

 

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

isset(): Determines whether a variable is set and is not null, commonly used for form inputs or array elements.

if (isset($_POST['submit'])) {
                            // Form submitted
                        }

 

16. Explain the difference between single quoted strings and double quoted strings in PHP.

Single quoted strings: Treat escape sequences and variables literally. Double quoted strings: Interpret escape sequences and allow variable interpolation.

$name = 'John';
                        $message = "Hello, $name!";

 

17. How can you access the length of a string in PHP?

You can use: the strlen() function to access the length of a string.

$length = strlen($string);

 

18. What are namespaces in PHP?

Namespaces: Used to encapsulate classes, functions, and constants, preventing naming conflicts and improving code organization.

namespace MyNamespace;
                        class MyClass {}

 

19. What is the purpose of the static keyword in PHP?

The static keyword: Used to declare properties and methods that belong to the class itself, rather than to instances of the class.

class MyClass {
                            public static $count = 0;
                        }

 

20. How can you redirect the user to another page in PHP?

You can use: the header() function with the 'Location' header set to the URL of the destination page.

header('Location: http://www.example.com');
                        exit();

 

21. Explain the purpose of the array_merge() function in PHP.

The array_merge() function in PHP is used to merge two or more arrays into a single array. For example:

$array1 = array("a", "b", "c");
                        $array2 = array(1, 2, 3);
                        $result = array_merge($array1, $array2);
                        print_r($result); // Output: Array ( [0] => a [1] => b [2] => c [3] => 1 [4] => 2 [5] => 3 )

 

22. What is the difference between array_push() and array_pop() functions in PHP?

The array_push() function is used to add one or more elements to the end of an array, while the array_pop() function is used to remove and return the last element from an array. For example:

$stack = array("orange", "banana");
                        array_push($stack, "apple");
                        print_r($stack); // Output: Array ( [0] => orange [1] => banana [2] => apple )
                        $fruit = array_pop($stack);
                        print_r($fruit); // Output: apple

 

23. How can you create a cookie in PHP?

Cookies in PHP can be set using the setcookie() function. For example:

setcookie("username", "John Doe", time() + 3600, "/");

 

24. Explain the purpose of the $_SESSION variable in PHP.

The $_SESSION variable in PHP is a superglobal variable used to store session data across multiple pages for a particular user. For example (setting session data):

session_start();
                        $_SESSION['username'] = 'John';

 

25. What is the use of the count() function in PHP?

The count() function in PHP is used to count the number of elements in an array or the properties in an object. For example:

$array = array(1, 2, 3, 4, 5);
                        echo count($array); // Output: 5

 

26. How can you execute a PHP script from the command line?

You can execute a PHP script from the command line using the PHP interpreter followed by the script name. For example:

php script.php

 

27. What are the magic methods in PHP?

Magic methods in PHP are special methods with predefined names that are triggered in response to certain actions in an object. Examples include __construct(), __destruct(), __toString(), etc.

 

28. Explain the purpose of the __construct() function in PHP.

The __construct() function in PHP is a constructor method that is automatically called when an object is created from a class. For example:

class MyClass {
                        public function __construct() {
                        echo 'Constructor called';
                        }
                        }
                        $obj = new MyClass(); // Output: Constructor called

 

29. What is the use of the json_encode() function in PHP?

The json_encode() function in PHP is used to convert a PHP array or object into a JSON string. For example:

$data = array("name" => "John", "age" => 30);
                        echo json_encode($data); // Output: {"name":"John","age":30}

 

30. How can you upload files in PHP?

Files in PHP can be uploaded using HTML forms with enctype="multipart/form-data" and handling the upload in PHP using $_FILES superglobal. For example (HTML form):

Example (PHP handling):

$target_dir = "uploads/";
                        $target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
                        move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file);

 

31. What is the use of the htmlspecialchars() function in PHP?

The htmlspecialchars() function in PHP is used to convert special characters to HTML entities. This is particularly useful when displaying user input on a webpage to prevent Cross-Site Scripting (XSS) attacks.

Example:

$input = "<script>alert('XSS attack!');</script>";
$safe_output = htmlspecialchars($input);
echo $safe_output; // Output: &lt;script&gt;alert('XSS attack!');&lt;/script&gt;

 

32. Explain the purpose of the ternary operator(?:) in PHP.

The ternary operator (?:) in PHP is a shorthand for an if-else statement. It evaluates a condition and returns one value if the condition is true, and another value if the condition is false.

Example:

$is_logged_in = true;
$message = ($is_logged_in) ? "Welcome back!" : "Please log in.";
echo $message; // Output: Welcome back!
$is_admin = false;
$user_role = ($is_admin) ? "Admin" : "User";
echo $user_role; // Output: User

 

33. How can you handle errors in PHP?

Errors in PHP can be handled using error handling functions like error_reporting(), ini_set(), set_error_handler(), and set_exception_handler(). Additionally, try-catch blocks can be used to handle exceptions.

 

34. What is the use of the date() function in PHP?

The date() function in PHP is used to format a timestamp or current date/time into a human-readable format. It returns a formatted date string.

Example:

echo date("Y-m-d"); // Output: Current date in YYYY-MM-DD format

 

35. Explain the difference between abstract classes and interfaces in PHP.

Abstract classes in PHP can contain both regular methods and abstract methods (methods without a body), while interfaces can only contain method signatures (method names and parameters) without any implementation. A class can implement multiple interfaces, but it can extend only one abstract class. Additionally, abstract classes can have properties, but interfaces cannot.

 

36. What is the use of the file_get_contents() function in PHP?

The file_get_contents() function in PHP is used to read the contents of a file into a string. It provides a simple way to read the entire contents of a file into a single string variable.

Example:

$content = file_get_contents("example.txt");
echo $content; // Output: Contents of the example.txt file

 

37. How can you connect to a MySQL database in PHP?

You can connect to a MySQL database in PHP using the mysqli or PDO extension. Here's an example using mysqli:

$servername = "localhost";
$username = "username";
$password = "password";
$database = "dbname";
// Create connection
$conn = new mysqli($servername, $username, $password, $database);
// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}
echo "Connected successfully";

 

38. What is the use of the die() function in PHP?

The die() function in PHP is used to display a message and terminate the script execution. It's often used for error handling or to stop the script execution based on certain conditions.

 

39. Explain the purpose of the array_shift() function in PHP.

The array_shift() function in PHP is used to remove the first element from an array and return it. It also decrements the array's length by one.

 

40. How can you create a function in PHP?

You can create a function in PHP using the function keyword followed by the function name and its parameters (if any). Here's an example:

function greet($name) {
    echo "Hello, $name!";
}
// Call the function
greet("John"); // Output: Hello, John!

 

41. What is the use of the array_key_exists() function in PHP?

The array_key_exists() function in PHP is used to check whether a specified key exists in an array or not. It returns true if the key exists and false otherwise.

 

42. How can you format a number with leading zeros in PHP?

You can use the sprintf() function in PHP to format a number with leading zeros.

Example:

$num = 7;
$formatted_num = sprintf("%02d", $num);
echo $formatted_num; // Output: 07

 

43. Explain the difference between array_merge() and array_combine() functions in PHP.

  • array_merge() is used to merge two or more arrays into a single array, combining their values.
  • array_combine() is used to create an array by using one array for keys and another for its corresponding values.

 

44. What is the use of the urlencode() function in PHP?

The urlencode() function in PHP is used to encode a string in a way that it can be safely used in a URL. It replaces special characters with a percent sign followed by two hexadecimal digits.

 

45. How can you handle file uploads larger than the maximum file size limit in PHP?

You can handle file uploads larger than the maximum file size limit in PHP by adjusting the upload_max_filesize and post_max_size directives in the php.ini configuration file. Additionally, you can check the file size before uploading using PHP and inform the user about the size limit.

 

46. Explain the purpose of the fclose() function in PHP.

The fclose() function in PHP is used to close an open file pointer. It's important to close files after you're done with them to free up resources and avoid potential issues.

 

47. What is the use of the array_search() function in PHP?

The array_search() function in PHP is used to search for a value in an array and return the corresponding key if the value is found. If the value is not found, it returns false.

 

48. How can you handle exceptions in PHP?

Exceptions in PHP can be handled using try, catch, and finally blocks. Code that may throw an exception is placed inside the try block, and exceptions are caught and handled inside the catch block.

 

49. What is the use of the array_reverse() function in PHP?

The array_reverse() function in PHP is used to reverse the order of elements in an array.

 

50. Explain the difference between require_once() and include_once() functions in PHP.

  • require_once() and include_once() are both used to include and evaluate a specified file in PHP.
  • require_once() throws a fatal error if the file cannot be included, whereas include_once() only emits a warning and continues script execution. Additionally, require_once() includes the file only once even if it's included multiple times, whereas include_once() includes the file multiple times if necessary.

 

51. What is the use of the htmlentities() function in PHP?

The htmlentities() function in PHP is used to convert characters to HTML entities. This is useful when displaying user input on a webpage to prevent XSS attacks.

 

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

You can remove duplicate values from an array in PHP using the array_unique() function.

Example:

$array = [1, 2, 2, 3, 4, 4, 5];
$unique_array = array_unique($array);
print_r($unique_array); // Output: [1, 2, 3, 4, 5]

 

53. What is the use of the var keyword in PHP?

The var keyword in PHP was used in earlier versions to declare class properties. However, it's no longer necessary and has been deprecated. You should use public, protected, or private keywords to declare class properties instead.

 

54. Explain the difference between $_GET and $_POST variables in PHP.

$_GET is used to collect data sent to the server as part of the URL, while $_POST is used to collect form data submitted by the POST method.

 

55. How can you loop through an associative array in PHP?

You can loop through an associative array in PHP using foreach loop.

Example:

$assoc_array = ['name' => 'John', 'age' => 30, 'city' => 'New York'];
foreach ($assoc_array as $key => $value) {
    echo "$key: $value <br>";
}

 

56. What is the use of the array_rand() function in PHP?

The array_rand() function in PHP is used to randomly select one or more keys from an array.

 

57. How can you sort an array in PHP?

You can sort an array in PHP using various functions like sort(), asort(), ksort(), etc., depending on your sorting requirements.

 

58. Explain the purpose of the file_put_contents() function in PHP.

The file_put_contents() function in PHP is used to write data to a file. It creates the file if it doesn't exist and overwrites the existing file content.

 

59. What is the use of the array_slice() function in PHP?

The array_slice() function in PHP is used to extract a slice of an array. It returns a portion of the array specified by the offset and length parameters.

 

60. How can you check if a variable is an array in PHP?

You can check if a variable is an array in PHP using the is_array() function.

Example:

$variable = [1, 2, 3];
if (is_array($variable)) {
    echo 'Variable is an array';
} else {
    echo 'Variable is not an array';
}

 

61. What is the use of the array_unique() function in PHP?

The array_unique() function in PHP is used to remove duplicate values from an array and return the resulting array with unique values only.

 

62. Explain the purpose of the array_column() function in PHP.

The array_column() function in PHP is used to return the values from a single column in an array. It extracts the values of a specified column from a multidimensional array and returns them as a single-dimensional array.

 

63. What is the use of the array_diff() function in PHP?

The array_diff() function in PHP is used to compare arrays and return the values from the first array that are not present in any of the other arrays.

 

64. How can you check if a string contains a specific substring in PHP?

You can check if a string contains a specific substring in PHP using the strpos() function or the strstr() function.

Example using strpos():

$string = "Hello, world!";
if (strpos($string, "world") !== false) {
    echo "Substring found";
} else {
    echo "Substring not found";
}

 

65. What is the use of the array_intersect() function in PHP?

The array_intersect() function in PHP is used to compare arrays and return the values that are present in all arrays.

 

66. Explain the difference between session_unset() and session_destroy() functions in PHP.

  • session_unset() function in PHP is used to unset all variables registered in a session.
  • session_destroy() function is used to destroy all data registered to a session.

 

67. How can you convert a string to uppercase in PHP?

You can convert a string to uppercase in PHP using the strtoupper() function.

Example:

$string = "hello world";
$uppercase_string = strtoupper($string);
echo $uppercase_string; // Output: HELLO WORLD

 

68. What is the use of the array_chunk() function in PHP?

The array_chunk() function in PHP is used to split an array into chunks of a specified size.

 

69. Explain the purpose of the array_push() function in PHP.

The array_push() function in PHP is used to add one or more elements to the end of an array.

 

70. What is the use of the array_fill() function in PHP?

The array_fill() function in PHP is used to fill an array with values. It creates an array containing a specified number of elements, each initialized with the same value.

 

71. How can you check if a file exists in PHP?

You can check if a file exists in PHP using the file_exists() function. This function returns true if the file exists and false otherwise.

Example:

$file_path = '/path/to/your/file.txt';

if (file_exists($file_path)) {
    echo "File exists!";
} else {
    echo "File does not exist!";
}

 

72. Explain the difference between require() and include() functions in PHP.

  • require() and include() are both used to include and evaluate a specified file in PHP.
  • The difference lies in how they handle errors: require() will throw a fatal error and halt script execution if the file cannot be included, whereas include() only emits a warning and continues script execution.
  • Additionally, require() is used when the file being included is essential for the script's functionality, whereas include() is used when the file being included is optional.

 

73. What is the use of the array_filter() function in PHP?

The array_filter() function in PHP is used to filter elements of an array using a callback function. It returns a new array containing only the elements for which the callback function returns true.

Example:

$array = [1, 2, 3, 4, 5];

// Filter even numbers
$result = array_filter($array, function($value) {
    return $value % 2 == 0;
});

print_r($result); // Output: [2, 4]

 

74. How can you convert a string to lowercase in PHP?

You can convert a string to lowercase in PHP using the strtolower() function.

Example:

$string = "HELLO WORLD";
$lowercase_string = strtolower($string);
echo $lowercase_string; // Output: hello world

 

75. Explain the purpose of the array_key() function in PHP.

There is no built-in array_key() function in PHP. It seems there might be a typo, and it's likely referring to array_keys() function instead. If that's the case, the array_keys() function is used to return all the keys or a subset of the keys of an array.

 

76. What is the use of the array_sum() function in PHP?

The array_sum() function in PHP is used to calculate the sum of values in an array.

Example:

$array = [1, 2, 3, 4, 5];
$total = array_sum($array);
echo $total; // Output: 15

 

77. How can you check if a variable is empty in PHP?

You can check if a variable is empty in PHP using the empty() function.

Example:

$var = '';
if (empty($var)) {
    echo "Variable is empty";
} else {
    echo "Variable is not empty";
}

 

78. Explain the difference between array_push() and array_merge() functions in PHP.

  • array_push() is used to add one or more elements to the end of an array.
  • array_merge() is used to merge two or more arrays into a single array.

 

79. What is the use of the array_map() function in PHP?

The array_map() function in PHP is used to apply a callback function to each element of an array and return a new array with the modified elements.

Example:

$array = [1, 2, 3, 4, 5];
$result = array_map(function($value) {
    return $value * 2;
}, $array);

print_r($result); // Output: [2, 4, 6, 8, 10]

 

80. How can you sort an associative array by value in PHP?

You can sort an associative array by value in PHP using the asort() function.

Example:

$array = ['a' => 3, 'b' => 1, 'c' => 2];
asort($array);
print_r($array); // Output: ['b' => 1, 'c' => 2, 'a' => 3]

 

81. Explain the purpose of the array_diff_assoc() function in PHP.

The array_diff_assoc() function in PHP is used to compute the difference of arrays with additional index check, also known as the associative array difference. It compares the keys and values of two or more arrays and returns the differences.

 

82. What is the use of the array_walk() function in PHP?

The array_walk() function in PHP is used to apply a user-defined function to each element of an array.

 

83. How can you convert a PHP array to a JSON string?

You can convert a PHP array to a JSON string using the json_encode() function.

Example:

$array = ['name' => 'John', 'age' => 30, 'city' => 'New York'];
$json_string = json_encode($array);
echo $json_string;

 

84. Explain the difference between array_intersect_assoc() and array_intersect_key() functions in PHP.

  • array_intersect_assoc() compares the keys and values of two or more arrays and returns the intersection of arrays with additional index check.
  • array_intersect_key() compares the keys of two or more arrays and returns the intersection of arrays based on keys only.

 

85. What is the use of the array_combine() function in PHP?

The array_combine() function in PHP is used to create an array by using one array for keys and another array for its corresponding values. It combines the two arrays by matching their corresponding elements.

 

86. How can you remove a specific element from an array in PHP?

You can remove a specific element from an array in PHP using the unset() function or the array_splice() function.

Example using unset():

$array = [1, 2, 3, 4, 5];
unset($array[2]); // Remove element with index 2
print_r($array); // Output: [1, 2, 4, 5]

 

87. Explain the purpose of the array_flip() function in PHP.

The array_flip() function in PHP is used to exchange the keys with their associated values in an array. The original values become keys, and the original keys become values.

 

88. What is the use of the array_fill_keys() function in PHP?

The array_fill_keys() function in PHP is used to fill an array with values specified by a value parameter, indexed by the keys specified by keys parameter.

 

89. How can you check if a variable is set in PHP?

You can check if a variable is set in PHP using the isset() function.

Example:

$var = 'Hello';
if (isset($var)) {
    echo "Variable is set";
} else {
    echo "Variable is not set";
}

 

90. Explain the difference between isset() and empty() functions in PHP.

  • isset() returns true if the variable exists and is not null.
  • empty() returns true if the variable exists and is considered empty (i.e

., has a value that evaluates to false).

 

91. What is the use of the array_map() function in PHP?

The array_map() function in PHP is used to apply a callback function to each element of an array and return a new array with the modified elements.

 

92. How can you shuffle an array in PHP?

You can shuffle an array in PHP using the shuffle() function.

Example:

$array = [1, 2, 3, 4, 5];
shuffle($array);
print_r($array); // Output: shuffled array

 

93. Explain the purpose of the array_values() function in PHP.

The array_values() function in PHP is used to return all the values of an array and re-index the array numerically.

 

94. What is the use of the array_pop() function in PHP?

The array_pop() function in PHP is used to remove and return the last element from an array.

 

95. How can you check if a function exists in PHP?

You can check if a function exists in PHP using the function_exists() function.

Example:

if (function_exists('my_function')) {
    echo "Function exists";
} else {
    echo "Function does not exist";
}

 

96. Explain the difference between array_key_exists() and isset() functions in PHP.

  • array_key_exists() checks if a specific key exists in an array.
  • isset() checks if a variable is set and is not null.

 

97. What is the use of the array_product() function in PHP?

The array_product() function in PHP is used to calculate the product of values in an array.

 

98. How can you check if a key exists in an array in PHP?

You can check if a key exists in an array in PHP using the array_key_exists() function.

Example:

$array = ['a' => 1, 'b' => 2, 'c' => 3];
if (array_key_exists('b', $array)) {
    echo "Key exists";
} else {
    echo "Key does not exist";
}

 

99. Explain the purpose of the array_replace() function in PHP.

The array_replace() function in PHP is used to replace the values of the first array with the values from subsequent arrays. If a key exists in multiple arrays, the value from the last array will be used.

 

100. What is the use of the array_shift() function in PHP?

The array_shift() function in PHP is used to remove and return the first element from an array, shifting all other elements to a lower index.

These should cover all your questions with detailed explanations and examples. If you need further clarification or have additional questions, feel free to ask!