Q1. Who is the father of PHP?
A: Rasmus Lerdorf.
Q2: What is PHP?
A: PHP stands for “Hypertext Preprocessor”.
It’s a open source server-side scripting language that is widely used for web development.
It was created by Rasmus Lerdorf in 1994. It’s the server side programming language.
Q3: What are the different types of errors in PHP?
A: There are 3 types of errors in PHP.
a) Notices: Notices are non-critical errors, which comes when accessing a variable that has not been defined.By default, Notices are not displayed to the user.
b) Warnings: Warnings are more serious errors, which comes when calling include() a file which does not exist. By default, these errors are displayed to the user. Warnings do not result in script termination.
c) Fatal errors: Fatal errors are critical errors, which comes when calling a non-existent function or class. Fatal errors cause the immediate termination of the script.
Q4: What the difference is between include and require?
A: Require () and include () are the same with respect to handling failures. However, require () results in a fatal error and does not allow the processing of the page. i.e. include will allow the script to continue.
Both are used to include a file, but when included file does not found. Include send warning, where as require sends fatal error.
Q5: What are the advantages of PHP ?
A: Below are the advantages of PHPOPEN SOURCE
Database Integration
Built-In Libraries
Easy to learn
Portability
Free to access Sourcecode
Q6. How to submit a form without Submit button?
A: document.formname.submit();
Q7: Difference between array_merge and array_combine?
A: array_merge: Merges elements of one or more arrays together so that the values of one are appended to the end of the previous one.
Example:
$array2 = array(‘a’, ‘b’, ‘color’ => ‘green’, ‘shape’ => ‘trapezoid’, 4);
$result = array_merge($array1, $array2);
print_r($result);
?>
Output will:
Array
(
=> green
[0] => 2
[1] => 4
[2] => a
[3] => b
[shape] => trapezoid
[4] => 4
)
array_combine: Creates an array by using one array for keys and another for its values
Example:
Output will:
Array
(
[green] => goava
[yellow] => banana
[red] => apple
)
Q8: Can we include any file two times in file/page?
A: yes, but create problem when included file contains some functions declaration, then error will come for already declared functions and else if you want to show some content two times, no problem.
Q9: How to check:
IP Address of the server: $_SERVER[‘REMOTE_ADDR’]
Previous reference page: $_SERVER[‘HTTP_REFERER’]
Q10: What is the difference between Public, Private and Protected variables?
A: Public: Public declared items can be accessed anywhere.
Private: Private limits visibility to class that defines item.
Protected: Protected limits access to inherited, parent class and to the class that defines the item.
Q11:What are the different types of errors in PHP?
A: Notices: Non critical errors, like accessing a variable that has not been defined yet. Such errors are not displayed to users.
Warnings: More serious errors, like including a file that does not exist. These errors are displayed to the user but no script termination.
Fatal Errors: Critical errors, like calling non-existent function and causes immediate terminating of the script.
Q12: Difference between strstr and stristr?
A: Strstr: returns the part of string from the first occurrence of the needle to the end of the string.
Example: $email = “abc@solutionsbased.in”;
$domain = strstr($email, ‘@’); echo $domain;
// Output: @solutionsbased.in
Stristr: is case-sensitive.
Q13: How to set the default timezone?
A: date_default_timezone_set();
Q14: Difference between unlink and unset()?
A: unlink(): Delete the given file from the system.
unset():Makes a variable undefined.
Q15. Which PHP functions combines two arrays?
A: array_merge();
Q16. What is the collection of characters that is treated as entity called?
A: String
Q17. Self contained collection of functions AND properties are referred to as ?
A: Objects
Q18. Which function sets internal pointer of an array back to first element?
A: reset();
Q19. What is Document root in PHP?
A:$_SERVER[‘DOCUMENT_ROOT’] => The document root directory under which the current script is executing, as defined in the server’s configuration file.
Q20. What are Operators & its types?
A: Operators are used to perform operations on variables and values.
Types of Operators:
- Arithmetic operators
- Assignment operators
- Comparison operators
- Increment/Decrement operators
- Logical operators
- String operators
- Array operators
Q21. What is difference between explode and implode and split
A:explode() function breaks a string into an array.
Example: explode(separator,string,limit)
implode() function returns a string from the elements of an array.
Example: implode(separator,array)
split() function returns an array of strings after splitting up a string.
Q22. What is difference between Class & Object
A: Class is a structure that can contain properties and methods.
An object is a data type which stores data and information on how to process that data.
First we must declare a class of object. For this, we use the class keyword.
Example
}
}
// create an object
$data = new Student();
// show object properties
echo $data->name;
?>
Q22. What are Regular Expressions? Write regular expression for validation of email
A: Regular expressions are nothing more than a sequence or pattern of characters itself.
They provide the foundation for pattern-matching functionality.
– We can search a particular string inside a another string
– We can replace one string by another string
– We can split a string into many chunks.
if ( preg_match( “^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$” , “abc@test.com” ) ) {
echo “Valid email”;
}
Q23. What is difference between Function Overloading and Function Overriding? Explain with Examples.
A: Function Overloading:
Overloading is calling the same function different parameters.
Example:
——-
class GetUserDetails {
function getDetails($firstName, $LastName) {
return $firstName+$LastName;
}
function getDetails($firstName, $LastName, $Age) {
return $firstName+$secondName+$Age;
}
}
— Function Overloading is not yet supported in PHP but, you can only overload methods using the magic methods __call(), __get(), __set(), __isset(), __unset(), __sleep(), __wakeup() etc.
Function Overriding:
Overriding occurs when you extend a class and rewrite a function which existed in the parent class
Example:
——-
class ParentClass {
public function getUsersData(){
return ‘Parent’;
}
}
class UserClass extends ParentClass {
public function getUsersData(){
return ‘User’;
}
}
$users = new UserClass();
echo $users->getUsersData(); //It will call child function of UserClass instead of parent.
Q24. What are Magic methods in PHP?
A: The “magic” methods are ones with special names, starting with two underscores, which denote methods which will be triggered in response to particular PHP events.
The “magic” methods are ones with special names, starting with two underscores, which denote methods which will be triggered in response to particular PHP events.
Q25. What is the use of ob_start()
A: It is used to active the output buffering. When output buffering is on all output of the page will be sent at one time to the browser, otherwise we will face “headers already sent” error.
Q26. What are the different states of Ajax?
A: There are 5ready state in ajax.
0: request not initialized (uninitialized)
1: server connection established (loading)
2: request received (loaded)
3: processing request (interactive)
4: request finished and response is ready (complete)
Q26. What is array_flip?
A: array_flip exchange the keys with their associated values in array. So keys becomes values and values becomes keys
Q27. What are the differences between include and require in PHP?
A: include and require are used to include files in PHP.
– include: If the included file is not found, a warning is issued, but the script will continue to execute.
– require: If the required file is not found, a fatal error occurs, and the script stops executing.
Q28. What is the difference between GET and POST methods in PHP?
A: GET: Sends data in the URL (visible in the browser), limited in size, and can be bookmarked. It is mainly used for retrieving data.
POST: Sends data in the body of the HTTP request, not visible in the URL, and has no size limitation. It is used for sending data (like form submissions).
Q29. What are cookies and sessions in PHP?
A: Cookie is a small file that the server sends to the browser to store on the client-side. This file contains data that can be retrieved on subsequent requests. You can set a cookie using setcookie() function and retrieve it using $_COOKIE.
A session in PHP allows you to store user information across different pages. Unlike cookies, session data is stored on the server and can be accessed using the $_SESSION superglobal array.
Q30. How do you handle exceptions in PHP?
A:
try {
// Code that may throw an exception
} catch (Exception $e) {
// Exception handler
echo “Caught exception: ” . $e->getMessage();
}
Q31. Differences between static, abstract, and final classes/methods?
A: static: Defines class-level properties and methods that belong to the class itself, rather than to instances. Static members can be accessed without creating an object.
abstract: Used for classes and methods that must be extended or implemented by subclasses. Abstract classes cannot be instantiated, and abstract methods must be implemented by concrete subclasses.
final: Prevents a class from being inherited or a method from being overridden. Final methods and classes cannot be modified by subclasses.
Q32. What is the difference between a static and a non-static method in PHP?
A: static: A static method can be called without creating an instance of the class. It can only access other static members of the class.
non-static: A non-static method requires an instance of the class to be called and can access both static and non-static members.
Q33. What is an array in PHP? How many types of arrays are there?
A: An array in PHP is a data structure that stores multiple values in a single variable. PHP supports three types of arrays:
– Indexed Array: Arrays with numeric indexes.
– Associative Array: Arrays with named keys.
– Multidimensional Array: Arrays containing one or more arrays.
Q34. How can you sort an array in PHP?
A: sort(): Sorts an array in ascending order.
rsort(): Sorts an array in descending order.
asort(): Sorts an associative array by values in ascending order.
ksort(): Sorts an associative array by keys in ascending order
Q35. How do you iterate over an associative array?
A: You can use a foreach loop.
Example:
$assocArray = [“name” => “John”, “age” => 30];
foreach ($assocArray as $key => $value) {
echo “$key: $value\n”;
}
Q36. How do you combine two arrays into an associative array?
A: Use the array_combine() function. The first array will be used as keys, and the second array will be used as values.
Example:
$keys = [“name”, “age”, “city”];
$values = [“John”, 30, “New York”];
$assocArray = array_combine($keys, $values);
print_r($assocArray);
// Output : Array ( [name] => John [age] => 30 [city] => New York )
Q36. Explain the concept of namespaces in PHP?
A: Namespaces in PHP organize code and avoid name conflicts between classes, functions, and constants by encapsulating them under a unique scope.
Example:
namespace App\Controllers;
class User { }
Q37. What is the purpose of __construct and __destruct methods in PHP?
A: __construct: Automatically called when an object is created, often used to initialize properties.
__destruct: Automatically called when an object is destroyed, often used for cleanup tasks (e.g., closing database connections).
Q38. What are traits in PHP, and how are they used?
A: Traits are reusable pieces of code that add functionality to classes. They solve the problem of single inheritance by allowing multiple traits to be included in a class.
Example:
trait Logger {
public function log($message) {
echo $message;
}
}
Q39. What are some design patterns commonly used in PHP projects?
A: Common patterns include Singleton, Factory, Observer, MVC (Model-View-Controller), Dependency Injection, and Repository patterns
Q40. How do you optimize PHP scripts for performance?
A: Use opcode caching (e.g., OPcache).
Avoid unnecessary loops and large memory-consuming variables.
Use prepared statements for database queries.
Minimize I/O operations.
Optimize database queries with indexing.
Q41. What is Composer, and how do you use it in PHP projects?
A: Composer is a dependency manager for PHP. It allows you to install, update, and autoload libraries using the composer.json file.
Example:
composer require vendor/package
Q42. How do you handle RESTful API development in PHP?
A: Use frameworks like Laravel or Slim for routing and middleware.
Use JSON for request/response data.
Implement proper HTTP methods (GET, POST, PUT, DELETE).
Handle authentication (e.g., OAuth or tokens).
Validate and sanitize user input to ensure security.