1. What is a variable in PHP?
Show Answer
Ans. A variable in PHP is a symbol or name that represents a value. Variables are declared with a dollar sign ($
) followed by the variable name. For example, $myVariable = "Hello, PHP!";
creates a variable named myVariable
that holds the string value "Hello, PHP!".
2. What is an array in PHP?
Show Answer
Ans. An array in PHP is a data structure that can hold multiple values in a single variable. PHP supports both indexed arrays (with numeric keys) and associative arrays (with named keys). For example:
$indexedArray = array(1, 2, 3);
$associativeArray = array("key1" => "value1", "key2" => "value2");
3. What is a function in PHP, and how do you define one?
Show Answer
Ans. A function in PHP is a block of code that performs a specific task and can be reused throughout the program. Functions are defined using the function
keyword. For example:
function myFunction() {
echo "Hello from myFunction!";
}
4. What is an object in PHP?
Show Answer
Ans. An object in PHP is an instance of a class. Objects can contain both data (properties) and functions (methods) that operate on the data. Object-oriented programming in PHP allows for encapsulation, inheritance, and polymorphism. For example:
class MyClass {
public $property;
public function myMethod() {
echo "Hello from myMethod!";
}
}
$myObject = new MyClass();
$myObject->property = "Some value";
5. What is a string in PHP?
Show Answer
Ans. A string in PHP is a sequence of characters enclosed in single quotes ('
) or double quotes ("
). Strings can be manipulated using various built-in functions. For example:
$myString = "Hello, World!";
echo strlen($myString); // Outputs the length of the string
6. What are superglobals in PHP?
Show Answer
Ans. Superglobals are built-in global arrays in PHP that are always accessible, regardless of scope. Common superglobals include $_GET
, $_POST
, $_SESSION
, and $_COOKIE
. They are used to handle form data, session management, and more.
7. What is error handling in PHP?
Show Answer
Ans. Error handling in PHP involves managing errors that occur during script execution. PHP provides several functions for error handling, such as try
, catch
, and throw
for exceptions. You can also set custom error handlers using set_error_handler()
to define how errors should be handled.
8. What is the difference between echo and print in PHP?
Show Answer
Ans. Both echo
and print
output data to the screen. However, echo
can take multiple parameters and is slightly faster, while print
returns a value (1), so it can be used in expressions.
9. What is the difference between == and === in PHP?
Show Answer
Ans. ==
checks for value equality regardless of type, while ===
checks for both value and data type equality.
10. What are PHP sessions?
Show Answer
Ans. PHP sessions are used to store user information across multiple pages. They maintain user state by storing data on the server using the $_SESSION
superglobal.
11. How do cookies differ from sessions?
Show Answer
Ans. Cookies store data on the client’s browser, while sessions store data on the server. Cookies persist after the browser is closed (based on expiration), while session data is typically lost when the session ends.
12. How do you connect to a MySQL database in PHP?
Show Answer
Ans. You can connect using mysqli_connect()
or PDO. Example using mysqli:
$conn = mysqli_connect("localhost", "username", "password", "database");
13. What is PDO in PHP?
Show Answer
Ans. PDO (PHP Data Objects) is a database access layer providing a uniform method of access to multiple databases, supporting secure and flexible database interactions.
14. What are magic methods in PHP?
Show Answer
Ans. Magic methods are special functions in PHP that start with __
, like __construct()
, __destruct()
, __get()
, __set()
, and __toString()
. They are automatically called in certain scenarios.
15. What is a constructor and destructor in PHP?
Show Answer
Ans. A constructor (__construct()
) is called when an object is created. A destructor (__destruct()
) is called when the object is destroyed or the script ends.
16. How do you handle exceptions in PHP?
Show Answer
Ans. PHP handles exceptions using try
, catch
, and optionally finally
blocks. throw
is used to trigger exceptions manually.
17. What are include, require, include_once, and require_once?
Show Answer
Ans. These functions are used to include files. require
causes a fatal error if the file is missing; include
gives a warning. The _once
versions prevent multiple inclusions.
18. What is the difference between GET and POST methods in PHP?
Show Answer
Ans. GET
appends data to the URL and is suitable for non-sensitive data. POST
sends data in the HTTP body and is used for secure or large data submissions.
19. What is a namespace in PHP?
Show Answer
Ans. Namespaces help avoid name conflicts in larger applications by encapsulating classes, functions, and constants. Defined using the namespace
keyword.
20. How do you send emails using PHP?
Show Answer
Ans. PHP uses the mail()
function to send emails. For example: mail($to, $subject, $message, $headers);
21. What is the difference between isset() and empty()?
Show Answer
Ans. isset()
checks if a variable is set and not null, while empty()
checks if a variable has a "falsy" value like 0, "", null, or false.
22. What are traits in PHP?
Show Answer
Ans. Traits are a mechanism for code reuse in single inheritance languages. A trait allows developers to reuse sets of methods in multiple classes.
23. What is type hinting in PHP?
Show Answer
Ans. Type hinting specifies the expected data type of function arguments and return values, enhancing code clarity and reducing bugs.
24. How can you prevent SQL injection in PHP?
Show Answer
Ans. Use prepared statements with PDO or MySQLi to safely handle user inputs and avoid SQL injection attacks.
25. What is output buffering in PHP?
Show Answer
Ans. Output buffering allows you to store output data in an internal buffer instead of immediately sending it to the browser. Useful for headers and performance.
26. How do you redirect in PHP?
Show Answer
Ans. Use the header()
function to redirect: header("Location: page.php");
followed by exit;
.
27. What is Composer in PHP?
Show Answer
Ans. Composer is a dependency manager for PHP. It allows you to manage project libraries and automatically install or update packages.
28. What are access modifiers in PHP?
Show Answer
Ans. PHP supports public
, private
, and protected
modifiers to control access to class members.
29. What is autoloading in PHP?
Show Answer
Ans. Autoloading automatically includes class files when objects are instantiated. It’s commonly handled using spl_autoload_register()
or Composer.
30. What are some common security practices in PHP?
Show Answer
Ans. Common practices include input validation, output sanitization, using prepared statements, setting proper permissions, using HTTPS, and keeping PHP and dependencies up to date.
31. What is the use of the explode() function in PHP?
Show Answer
Ans. The explode()
function splits a string into an array using a delimiter. Example:
$arr = explode(",", "apple,banana,orange");
32. What is the difference between static and dynamic websites in PHP?
Show Answer
Ans. Static websites show the same content to all users, while dynamic websites generate content based on user interaction, often using PHP to fetch and display data dynamically.
33. What is the use of the isset() function?
Show Answer
Ans. isset()
checks if a variable is set and is not null. It returns true if the variable exists and is not null.
34. How do you define a constant in PHP?
Show Answer
Ans. You define a constant using the define()
function:
define("SITE_NAME", "MyWebsite");
35. What are PHP interfaces?
Show Answer
Ans. Interfaces allow you to define methods that must be implemented in a class. They support abstraction and help in designing loosely coupled systems.
36. What is the difference between abstract class and interface in PHP?
Show Answer
Ans. An abstract class can have method implementations, while an interface cannot. A class can implement multiple interfaces but only extend one abstract class.
37. What is the use of the final keyword in PHP?
Show Answer
Ans. The final
keyword prevents a method from being overridden or a class from being inherited.
38. What is the use of the header() function in PHP?
Show Answer
Ans. header()
sends raw HTTP headers to the browser. It is commonly used for redirection, content type, or caching headers.
39. How can you get the current date and time in PHP?
Show Answer
Ans. Use the date()
function:
echo date("Y-m-d H:i:s");
40. What is a callback function in PHP?
Show Answer
Ans. A callback is a function passed as an argument to another function, often used in array functions like array_map()
, usort()
, etc.
41. What is the difference between unset() and unlink()?
Show Answer
Ans. unset()
destroys a variable, while unlink()
deletes a file from the file system.
42. What is the difference between while and do-while loops in PHP?
Show Answer
Ans. A while
loop checks the condition before execution, whereas do-while
executes the block at least once before checking the condition.
43. What is the use of the die() function in PHP?
Show Answer
Ans. die()
prints a message and terminates script execution. It's commonly used for error handling.
44. How do you start a PHP session?
Show Answer
Ans. Use session_start();
at the beginning of the script to start a session and access $_SESSION
variables.
45. How do you destroy a session in PHP?
Show Answer
Ans. Use session_destroy();
to end a session and clear session data.
46. How do you create a file in PHP?
Show Answer
Ans. Use fopen()
to create or open a file. For example:
$file = fopen("newfile.txt", "w");
47. How do you read a file in PHP?
Show Answer
Ans. You can use fread()
, fgets()
, or file_get_contents()
depending on the need. Example:
$content = file_get_contents("file.txt");
48. How do you write to a file in PHP?
Show Answer
Ans. Use fwrite()
after opening a file in write mode. Example:
fwrite($file, "Hello, file!");
49. What are global variables in PHP?
Show Answer
Ans. Variables declared outside a function are global. Use the global
keyword inside functions to access them.
50. What is the use of $_SERVER in PHP?
Show Answer
Ans. $_SERVER
is a superglobal that provides information about headers, paths, and script locations. Example:
$_SERVER['HTTP_USER_AGENT']
gives the user's browser info.
51. What is the difference between require and include in PHP?
Show Answer
Ans. Both require
and include
are used to include and evaluate files. The difference is that require
causes a fatal error if the file is not found, whereas include
only raises a warning.
52. What is the difference between GET and POST methods in PHP?
Show Answer
Ans. GET
appends data to the URL and has length restrictions, while POST
sends data in the request body, making it more secure for sensitive data.
53. What are magic constants in PHP?
Show Answer
Ans. Magic constants are predefined constants like __LINE__
, __FILE__
, __DIR__
, __FUNCTION__
, etc., that change depending on where they are used.
54. What are traits in PHP?
Show Answer
Ans. Traits are a mechanism for code reuse in single inheritance. A trait is similar to a class, but it is intended to group functionality in a fine-grained and consistent way.
55. What is the difference between public, private, and protected in PHP?
Show Answer
Ans. public
members are accessible from anywhere, private
only within the class, and protected
within the class and its subclasses.
56. What is the use of the filter_var() function?
Show Answer
Ans. filter_var()
filters a variable with a specified filter, like validating emails or sanitizing strings. Example:
filter_var($email, FILTER_VALIDATE_EMAIL);
57. How do you handle errors in PHP?
Show Answer
Ans. PHP has functions like error_reporting()
, set_error_handler()
, and exception handling with try-catch
blocks.
58. What is the difference between session and cookie?
Show Answer
Ans. A session is stored on the server, while a cookie is stored in the user's browser. Sessions are more secure than cookies for storing sensitive data.
59. What is the use of mysqli and PDO in PHP?
Show Answer
Ans. Both are used for accessing databases. mysqli
is specific to MySQL, while PDO
supports multiple databases and provides an abstraction layer.
60. How can you prevent SQL injection in PHP?
Show Answer
Ans. Use prepared statements with bound parameters (e.g., using mysqli_prepare()
or PDO::prepare()
) to prevent SQL injection.
61. What is the difference between echo and print in PHP?
Show Answer
Ans. echo
can output multiple strings and is slightly faster. print
returns a value (1), so it can be used in expressions.
62. How do you define and use an associative array in PHP?
Show Answer
Ans. Associative arrays use named keys. Example:
$person = array("name" => "John", "age" => 30);
63. What is the difference between == and === in PHP?
Show Answer
Ans. ==
compares values after type juggling, while ===
checks both value and type.
64. What is the use of var_dump()?
Show Answer
Ans. var_dump()
displays structured information about a variable, including type and value. Useful for debugging.
65. What are anonymous functions in PHP?
Show Answer
Ans. Anonymous functions are functions without a name, often used as callbacks:
$greet = function($name) { return "Hello $name"; };
66. How do you redirect to another page in PHP?
Show Answer
Ans. Use the header("Location: page.php");
function to redirect. Ensure no output is sent before calling it.
67. What is output buffering in PHP?
Show Answer
Ans. Output buffering allows you to capture output and control when it is sent to the browser using functions like ob_start()
and ob_get_clean()
.
68. What is the difference between include() and include_once()?
Show Answer
Ans. include()
includes a file every time it's called, while include_once()
includes it only once, preventing multiple inclusions.
69. What is autoloading in PHP?
Show Answer
Ans. Autoloading allows classes to be loaded automatically when needed using spl_autoload_register()
, avoiding manual require
statements.
70. What is a namespace in PHP?
Show Answer
Ans. Namespaces help avoid name conflicts by encapsulating classes, functions, and constants. Declared using namespace
keyword.
71. What is Composer in PHP?
Show Answer
Ans. Composer is a dependency manager for PHP. It allows you to install and manage libraries your project depends on.
72. What is PSR in PHP?
Show Answer
Ans. PSR stands for PHP Standard Recommendation. It's a set of coding standards and best practices accepted by the PHP-FIG group.
73. What is a closure in PHP?
Show Answer
Ans. A closure is an anonymous function that can capture variables from the surrounding scope using the use
keyword.
74. What are superglobals in PHP?
Show Answer
Ans. Superglobals are built-in variables like $_GET
, $_POST
, $_SESSION
, $_SERVER
, and $_COOKIE
that are available in all scopes.
75. What is the difference between htmlentities() and htmlspecialchars()?
Show Answer
Ans. htmlspecialchars()
converts special characters to HTML entities, while htmlentities()
converts all applicable characters to entities.
76. What is the use of the list() function in PHP?
Show Answer
Ans. list()
is used to assign values to a list of variables in one operation. Example: list($a, $b) = array(1, 2);
77. What is the difference between array_merge() and array_combine()?
Show Answer
Ans. array_merge()
merges multiple arrays. array_combine()
creates an array using one array for keys and another for values.
78. What is the difference between explode() and str_split()?
Show Answer
Ans. explode()
splits a string by a delimiter. str_split()
splits a string into an array of characters or fixed-length segments.
79. How do you send an email using PHP?
Show Answer
Ans. Use the mail()
function: mail($to, $subject, $message, $headers);
80. What are the types of errors in PHP?
Show Answer
Ans. Common error types: Parse errors, Fatal errors, Warning, Notice, and Deprecated warnings.
81. What is the use of the instanceof operator?
Show Answer
Ans. instanceof
checks if an object is an instance of a specific class or implements an interface.
82. How do you implement inheritance in PHP?
Show Answer
Ans. Use the extends
keyword to create a subclass from a parent class.
83. How do you check if a key exists in an array?
Show Answer
Ans. Use array_key_exists()
or isset()
if you're checking for set and non-null keys.
84. What is the difference between file_get_contents() and fread()?
Show Answer
Ans. file_get_contents()
reads a file into a string. fread()
reads a file resource with a defined length.
85. What is a recursive function in PHP?
Show Answer
Ans. A recursive function calls itself to solve smaller instances of the same problem, useful in tree or directory traversal.
86. What is the difference between count() and sizeof()?
Show Answer
Ans. Both return the number of elements in an array. sizeof()
is an alias of count()
.
87. How do you define constants using class in PHP?
Show Answer
Ans. Use the const
keyword inside a class:
class MyClass { const VERSION = '1.0'; }
88. What is the use of get_class() function?
Show Answer
Ans. get_class()
returns the name of the class of an object.
89. What is a generator in PHP?
Show Answer
Ans. A generator allows you to iterate over a set of data without needing to build an array in memory using yield
.
90. What is the difference between interface and trait?
Show Answer
Ans. Interface defines a contract, while traits provide reusable method implementations. Classes can implement multiple interfaces and use multiple traits.
91. What are static methods in PHP?
Show Answer
Ans. Static methods belong to the class rather than an instance and are declared using the static
keyword.
92. What is type hinting in PHP?
Show Answer
Ans. Type hinting allows you to specify the expected data types for arguments, return values, and properties in functions and methods.
93. What is the null coalescing operator in PHP?
Show Answer
Ans. ??
is the null coalescing operator. It returns the left operand if it exists and is not null; otherwise, it returns the right operand.
94. What is the spaceship operator in PHP?
Show Answer
Ans. The <=>
operator returns -1, 0, or 1 when the left side is respectively less than, equal to, or greater than the right side.
95. How do you parse JSON in PHP?
Show Answer
Ans. Use json_decode()
to parse JSON into a PHP array or object.
96. How do you convert data to JSON in PHP?
Show Answer
Ans. Use json_encode()
to convert PHP arrays or objects into a JSON string.
97. What is a destructor in PHP?
Show Answer
Ans. __destruct()
is a method called when there are no other references to a particular object, used for cleanup.
98. What is the use of __construct() in PHP?
Show Answer
Ans. __construct()
is a constructor method that initializes object properties when the object is created.
99. How do you check if a variable is empty in PHP?
Show Answer
Ans. Use the empty()
function to check if a variable is empty (i.e., "", 0, null, false, [], etc.).
100. What is the difference between isset() and empty()?
Show Answer
Ans. isset()
checks if a variable is set and not null. empty()
checks if a variable has an empty value.