0 Bewertungen 0% fanden dieses Dokument nützlich (0 Abstimmungen) 2 Ansichten 32 Seiten PHP 1
Das Dokument bietet eine umfassende Sammlung von über 60 PHP-Interviewfragen und -antworten für verschiedene Erfahrungsstufen, einschließlich grundlegender Konzepte, objektorientierter Programmierung, Fehlerbehandlung und Datenbankinteraktionen. Es hebt die Vielseitigkeit von PHP als serverseitige Skriptsprache hervor, die von großen Unternehmen verwendet wird, und erläutert grundlegende Funktionen wie die Handhabung von Formulardaten und die Verwendung von Sessions. Darüber hinaus werden Unterschiede zwischen PHP und anderen Technologien sowie die Verwendung von PHP in beliebten Content-Management-Systemen und Frameworks behandelt.
KI-verbesserte Titel und Beschreibungen
Copyright
© All Rights Reserved
Verfügbare Formate
Als PDF herunterladen oder online auf Scribd lesen
Zu den vorherigen Artikeln Weiter zu den nächsten Artikeln
php1 für später speichern
‘9/8125, 7:33 PM PHP Interview Questions and Anewers-2025 - GooksforGeeks
Search...
FullStack Course HTML CSS JavaScript TypeScript jQuery Angular ReactJS Next js
PHP Interview Questions and Answers -2025
Last Updated : 13 Sep, 2025
PHP is a popular server-side scripting language, widely known for its
efficiency in web development and versatility across various platforms.
PHP is extensively utilized by top companies such as Facebook,
WordPress, Slack, Wikipedia, MailChimp, and many more due to its
robust features and high performance.
In this article, we will provide the Top 60+ PHP Interview Questions
2025 designed for both freshers and experienced professionals with 3,
5, and 8 years of experience. Here, we cover everything, including core
PHP concepts, Object-Oriented Programming (OOP), error handling,
security practices, PHP frameworks, database interactions, and more.
Table of Content
* PHP Interview Questions for Beginners
+ PHP Interview Questions for Intermediate
ns for Advanced
© PHP Interview
* Top 10 Commonly asked PHP Interview Questions
PHP Interview Questions for Beginners
1. What is PHP?
PHP is a general-purpose programming language used to design a
website or web application. It is a server-side scripting language
embedded with HTML to develop a Static website, a Dynamic website,
and a Web application. It was created by Rasmus Lerdorf in 1994.
* Server-Side Language: PHP runs on the server, generating HTML or
other content,Destroys which is then sent to the client's browser.
-[Link]/php/php-intrview-questions-and-answers! 192‘9/8125, 7:33 PM PHP Interview Questions and Anewers-2025 - GooksforGeeks
: PHP can interact with databases and
* Dynamic Content Creatioi
process user input, making websites interactive and data-driven
* Cross-Platform: It works on various platforms, including Windows,
Linux, and macOS.
* Integration with Databases: PHP easily connects with databases like
MySQL, making it ideal for building dynamic, database-driven
websites.
* Open-Source: PHP is free to use, with a large community of
developers contributing to its ecosystem.
2. How do you redirect a page in PHP?
In PHP, you can redirect a user to a different page using the header()
function. This function sends a raw HTTP header to the browser, telling
it to navigate to a different URL.
header("Location: newpage. php");
exitQ);
3. What is the difference between session_unset() and
session_destroy()?
Both session_unset() and session_destroy() are used to manage session
data in PHP, but they serve different purposes:
session_unset() session_destroy()
Clears all session variables
Destroys and the session, removing all
{removes data), but session
data remains.
session data on the server.
The session ID remains valid The session ID becomes invalid after
after calling session_unset(). calling session_destroy()
-[Link]/php/php-intrview-questions-and-answers! 2132‘918125, 7:33 PM
session_unset()
Session data still exists on the
server, the session file is not
deleted.
Session persists; session
variables can be reused after
calling session_unset()
The session ID is available and
can be reused across requests.
Useful when you want to clear
data (e.g., logging out a user
but keeping the session alive).
PHP Interview Questions and Answers-2025 - GocksforGeoks
session_destroy()
The session file is removed from the
server (session data is deleted)
The session cannot be used again
unless a new session is created with
session_start()
After session destruction, a new
session ID needs to be created with
session_start().
Used when you want to completely
terminate the session (e.g., user logging
out and destroying all session data).
4. ls PHP a case-sensitive language?
Yes, PHP is a case-sensitive language for variables, but function names,
class names, and constants are not case-sensitive.
5. What is the difference between PHP and [Link]?
PHP [Link]
[Link] is a web application
framework using languages like Cif
and, [Link].
PHP is a server-side scripting
language.
Open-source, cross-platform Proprietary, primarily runs on
(works on Windows, Linux,
macOS).
Windows,, there is but can now run on
Linux with .NET Core.
-[Link]/php/php-intrview-questions-and-answers! 3132‘918125, 7:33 PM PHP Interview Questions and Answers-2025 - GocksforGeeks
PHP [Link]
Proprietary (though .NET Core is open-
Free and open-source.
source)
High performance for web- _ Generally, there is, higher performance
based applications, especially due to compiled code and
with PHP-FPM. optimizations in .NET.
6. How does PHP handle form data?
PHP handles form data through two main superglobals: $_GET and
$_POST.
* $_GET is used to collect form data sent through the URL (typically
from a query string). It's often used for search forms or when the data
should be visible in the URL.
$_POST is used to collect form data sent via HTTP POST, which is
more secure as the data is not visible in the URL. It's typically used for
sensitive data like login credentials or when submitting large
amounts of data.
N
|. What is the full form of PHP?
PHP is the abbreviation of Hypertext Preprocessor, the following and
earlier it was abbreviated as Personal Home Page.
8. What was the old name of PHP?
The old name of PHP was Personal Home Page.
9. What are the uses of PHP?
PHP is widely used for various tasks in web development. Some of its
key uses include the following and:
-[Link]/php/php-intrview-questions-and-answers! 4132‘9/8125, 7:33 PM PHP Interview Questions and Anewers-2025 - GooksforGeeks
It is a server-side scripting language used to design dynamic
websites or web applications
It receives data from forms to generate the dynamic page content.
It can work with databases and sessions, send and receive cookies,
send emails, etc.
It can be used to add, delete, and modify content within the database.
It can be used to set arerestriction to the user to access the web page.
10. What is PEAR in PHP?
PEAR(PHP Extension and Application Repository) is a framework and
distribution system for reusable PHP components. It stands for PHP
Extension and Application Repository. It contains PHP snippets and a
library to reuse the code. It provides a command-line interface to install
packages
Some of the key features of PEAR
Reusable Code
Package Management
Standardization
Autoloading
Command-line Interface (CLI)
Web-based Interface
11. What is the difference between static and dynamic websites?
Static Website: Content is fixed and doesn’t change unless manually
updated by the developer. Static Websites arelt may built using HTML,
CSS, and JavaScript; each page is a separate file.
Limited customization for the user; all visitors see the same content.
Faster load times since the content is already pre-built and served as-
is.
Easier to maintain; updating content requires manual edits to
individual pages.
* Generally cheaper to build and host.
-[Link]/php/php-intrview-questions-and-answers! 5132‘9/8125, 7:33 PM PHP Interview Questions and Anewers-2025 - GooksforGeeks
Dynamic Web:
Content is generated in real-time, often based on
user interaction or database queries, Built using server-side
technologies like PHP, [Link], or Nodejs, and may use databases to
retrieve content.
Content can change based on user input or preferences (e.g., login
systems, product catalogs).
May have slower load times due to real-time content generation and
database queries.
Requires backend management and database updates, which can be
more complex.
It mayneed be more expensive due to the need for server-side
scripting and database support.
12. What are the rules for naming a PHP variable?
The following two rules need to be followed while naming a PHP.
variable.
* Avariable in PHP must start with a dollar sign ($), followed by the
variable name. For example, Sprice = 100; where price is the variable
name.
Variable names must begin with a letter (a-z, A-Z) or an underscore
().
A variable name can consist of letters, numbers, or underscores, but
special characters like +, -, %, &, etc., are not allowed.
PHP variable names cannot contain spaces.
PHP variables are case-sensitive, meaning $NAME and $name are
considered different variables.
13. How to execute a PHP script from the command line?
Here, we mentioned the following PHP command line to run the PHP
program:
* Open terminal or command line window.
* Go to the specified folder or directory where PHP files are present.
* Then, we can run PHP code using the command php file_name.php
-[Link]/php/php-intrview-questions-and-answers! 61329/1825, 7:33 PM PHP Intrviow Questions and Answers -2025 - GeektorGeoks
* Start the server for testing the php code using the command php -s
localhost:port -t your_folder/
14. What is the most used method for hashing passwords in
PHP?
The crypt() function in PHP is another option for hashing passwords,
offering a wide variety of hashing algorithms like SHA-1, SHA-256, and
MDS. While these algorithms are fast and efficient, they are no longer
considered secure for hashing passwords due to their vulnerability to
brute-force and rainbow table attacks.
15. Does JavaScript interact with PHP?
Yes, JavaScript can interact with PHP, typically through AJAX
(Asynchronous JavaScript and XML). JavaScript sends requests to PHP
on the server, and PHP processes these requests and returns data (often
in JSON or HTML format) to JavaScript for further manipulation on the
client side without reloading the page.
Common use cases include
* Submitting forms without refreshing the page.
* Fetch data from a server dynamically.
* Updating content on a page based on user actions.
16. Explain the main types of errors.
The three main types of errors in PHP are:
Notices: Notices are non-critical errors that can occur during the
execution of the script. These are not visible to users. Example:
Accessing an undefined variable.
Warnings: These are more critical than notices. Warnings don’t
interrupt the script execution. By default, these are visible to the user.
Example: include() a file that doesn’t exist.
Fatal: This is the most critical error type, which, when occurs,
immediately terminates the execution of the script. Example:
-[Link]/php/php-intrview-questions-and-answers! 1329/1825, 7:33 PM PHP Intrviow Questions and Answers -2025 - GeektorGeoks
Accessing a property of a non-existent object or require() a non-
existent file.
17. How do you define a constant in PHP?
The define() function is a fundamental feature in PHP for PHP Defining
Constants.
* It serves to create and retrieve the value of a constant, which is an
identifier whose value remains fixed throughout the execution of a
script.
Unlike variables, constants are defined without the dollar sign ($) and
cannot be altered or undefined once set.
Constants are commonly used to store unchanging values such as the
domain name of a website (e.g., [Link]).
18. What are the popular frameworks in PHP?
Some of the most popular PHP frameworks are:
Laravel
Codelgniter
Symfony
CakePHP
* Yi
Zend Framework
Phalcon
FuelPHP.
PHPixie
Slim
19. What are the popular Content Management Systems (CMS)
in PHP?
Some popular Content Management Systems (CMS) written in PHP
include:
* WordPress: WordPress is a free and open-source Content
Management System(CMS) framework. It is the most widely used
-[Link]/php/php-intrview-questions-and-answers! 8132‘9/8125, 7:33 PM PHP Interview Questions and Anewers-2025 - GooksforGeeks
CMS framework of recent times.
Joomla: Joomla is a free and open-source content management
system (CMS) for distributing web content. It follows the model-
view-controller web application framework that can be used
independently.
Magento: It is an open-source and e-commerce platform to develop
online business.
Drupal: It is a content management system (CMS) platform
developed in PHP and distributed under the GNU (General Public
License).
20. What is the purpose of the break and continue statement?
The break and continue statements are used in loops and switch
statements to control the flow of execution.
* break: The break statement immediately terminates the whole
iteration of a loop, and the program control resumes at the next
statement following the loop.
continue: The continue statement skips the current iteration and
brings the next iteration early. The continue 2 acts as a terminator for
case and skips the current iteration of the loop.
21. What is the use of the count() function in PHP?
The PHP count() function counts the number of elements present in the
array. The function might return 0 for the variable that has been set to
an empty array. Also, for the variable which is not set, the function
returns 0.
22. What are the different types of loops in PHP?
PHP supports four different types of loop which are listed below:
* for loop
* while loop
+ do-while loop
* foreach loop
-[Link]/php/php-intrview-questions-and-answers! 9132‘9/8125, 7:33 PM PHP Interview Questions and Anewers-2025 - GooksforGeeks
PHP Interview Questions for Intermediate
23. What is the main difference between PHP 4 and PHP 5?
The main differences between PHP 4 and PHP 5 are:
Object-Oriented Programming (OOP) Support:
+ PHP 4 had limited object-oriented support. It used the concept of
"objects" but lacked many OOP features like access modifiers (private,
protected), constructors/destructors, and inheritance.
* PHP 5 introduced full-fledged object-oriented programming with
improved support for classes, interfaces, abstract classes,
constructors, destructors, and access modifiers.
Performance and Features:
* PHP 4 was based on a simpler Zend engine, which lacked several
optimizations present in newer versions.
PHP 5 introduced the Zend Engine II, providing better performance,
more efficient memory handling, and additional features like
exception handling, reflection, and PDO (PHP Data Objects) for
database abstraction.
XML Support:
* PHP 4 had limited XML support.
* PHP 5 included more robust XML support, with built-in extensions
like DOM and SimpleXML for easier XML parsing and manipulation.
Error Handling:
* PHP 4 used traditional error handling via the $php_errormsg global
variable.
+ PHP 5 introduced exception handling using try, catch, and throw
keywords for better control and readability.
Support for New Extensions:
-[Link]/php/php-intrview-questions-and-answers! 0132‘9/8125, 7:33 PM
PHP Interview Questions and Anewers-2025 - GooksforGeeks
* PHP 5 introduced many new extensions, including PDO for database
interaction and SOAP for web services, which were not available in
PHP 4.
24. Explain the importance of Parser in [Link] each
A PHP parser is a tool that converts PHP source code into a format that
the computer can interpret and execute. It translates the PHP
instructions into machine-readable code, allowing the server to process
and run the script. You can parse PHP code using the token_get_all()
function, which breaks down the PHP code into an array of tokens that
represent different parts of the code (like variables, keywords, operators,
etc).
25. What is the difference between for and foreach loop in PHP?
for Loop
When you know the number of
iterations
Requires initialization, condition,
and increment
Can access and modify array
indexes
More flexible, works for any
iteration type
Slightly faster for large datasets
with known indexes
foreach loop
When iterating over arrays or
collections
Directly iterates over array values
Provides direct access to values (and
optionally keys)
Simpler, focused on arrays and
collections
Can be slower in some cases but
more readable for arrays
26. How can PHP and HTML interact?
-[Link]/php/php-intrview-questions-and-answers!
82anes, 793M PHP Iterviow Questions and Answors-2025-GeottorGeoks
PHP scripts can generate HTML content and pass information from
HTML to PHP. While PHP is a server-side language, HTML operates on
the client side. PHP processes data on the server and returns results as
strings, objects, or arrays, which can then be displayed within HTML.
This interaction allows both languages to complement each other
effectively.
27. What are the main error types, and how do they differ?
There are various types of errors in PHP, but it contains four main
types of errors.
Parse error or Syntax Error: This is the type of error made by the
programmer in the source code of the program. Parse errors can be
caused dues to non-closed quotes, missing or extra parentheses,
non-closed braces, missing semicolon, etc.
Fatal Error: It is the type of error where PHP compiler understands
the PHP code but it recognizes an undeclared function. It means that
function is called without the definition of the function.
Warning Errors: The main reason for warning errors are including a
missing file. This means that the PHP function call the missing file.
Notice Error: It is similar to warning error. It means that the program
contains something wrong but it allows the execution of script.
28. What is inheritance in PHP ?
Inheritance in PHP is an object-oriented programming (OOP) concept
where a class (called the child or subclass) can inherit properties and
methods from another class (called the parent or superclass). This
allows the child class to reuse code from the parent class and extend or
modify its functionality.
29. Is PHP supports multiple inheritance ?
No, PHP does not support multiple inheritance directly, meaning a class
cannot inherit from more than one class. A class can only inherit from
one parent class, which is a limitation of PHP’s inheritance model.
-[Link]/php/php-intrview-questions-and-answers! arssy1825, 739M PHP Itrew Questions and Answors-2025- GekstorSeoks
However, PHP allows for multiple inheritance through interfaces. A
class can implement multiple interfaces, enabling it to inherit behavior
from more than one source.
30. What are Traits in PHP ?
Traits in PHP are a mechanism for code reuse in single inheritance
languages like PHP. They allow you to include methods in a class
without using inheritance, providing a way to share functionality across
multiple classes.
* Code Reuse: Traits allow you to reuse methods across different
classes without duplicating code.
Conflict Resolution: If multiple traits define a method with the same
name, PHP requires you to resolve the conflict by explicitly defining
which method to use.
No Instantiation: Traits cannot be instantiated on their own, they
must be included in a class.
31. What is difference between GET and POST?
GET: It requests data from a specified resource. In this method, the data
is sent as URL parameters that are usually strings of name and value
pairs separated by ampersands (8).
POST: In this method the data is sent to the server as a package in a
separate communication with the processing script. Data sent through
POST method will not be visible in the URL.
-[Link]/php/php-intrview-questions-and-answers! 19992sy1825, 739M PHP Itrew Questions and Answors-2025- GekstorSeoks
32. What is the difference between the unset() and unlink()
functions ?
Untink() function: The unlink() function is an inbuilt function in PHP
which is used to delete a file.
The filename of the file which has to be deleted is sent as a
parameter and the function returns True on success and False on
failure.
The unlink() function in PHP accepts two-parameters filename and
context.
Unset() function: The Unset() function is an inbuilt function in PHP
which is used to remove the content from the file by emptying it.
It means that the function clears the content of a file rather than
deleting it.
The unset{) function not only clears the file content but also used to
unset a variable, thereby making it empty accepts a single parameter
variable.
33. If x = 10 and y = “10” then what does the condition x
returns ?
The condition x === y checks for both value and type equality in PHP.
* x= 10is an integer.
* y="10" isa string
Since the values are the same (10), but their types are different (integer
vs string), the condition x
y will return false.
In PHP:
checks both the value and type.
only checks the value, allowing type conversion.
oO
$x = 10;
-[Link]/php/php-intrview-questions-and-answers! sais‘918125, 7:33 PM PHP Interview Questions and Anewers-2025 - GooksforGeeks
var_dump($x
$y)
?>
Output
bool (false)
34. What is Nullable types in PHP ?
This feature is new to PHP, Nullable adds a leading question mark
indicate that a type can also be null.
function geeks(): Pint {
return null;
}
35. What is the maximum size of a file that can be uploaded
using PHP?
By default maximum upload file size for PHP scripts is set to 128
megabytes. But you can change it. The maximum size of any file that can
be uploaded on a website written in PHP is determined by the values of
max_size that can be posted or uploaded, mentioned in the [Link] file of
the server.
36. What are PHP streams?
Streams are a way of abstracting input/output (I/O) operations, allowing
you to work with various data sources (like files, network connections, or
even in-memory data) in a consistent manner. Streams represent a
generalization of /O operations, enabling data to be read from or written
to a resource.
37. What is autoloading in PHP?
-[Link]/php/php-intrview-questions-and-answers! 45192sy1825, 739M PHP Itrew Questions and Answors-2025- GekstorSeoks
Autoloading in PHP is a mechanism that automatically loads classes,
interfaces, and traits when they are needed, without explicitly requiring
you to include or require the file where they are defined. This improves
code organization, reduces the need for multiple include or require
statements, and helps manage dependencies efficiently.
How Autoloading Works
* When a class is referenced (for example, when you instantiate a class
or calla method), PHP automatically looks for the corresponding file
containing the class definition.
If the file is not already included in the script, PHP uses an autoloader
function to locate and load the class file.
38. How can you prevent Cross-Site Scripting (XSS) in PHP?
Cross-Site Scripting (XSS) is a vulnerability where an attacker injects
malicious scripts into web pages viewed by other users. To prevent XSS
attacks in PHP use-
Escape Output (HTML Encoding): Encode user-generated content to
prevent it from being treated as executable code.
echo htmlspecialchars($user_input, ENT_QUOTES, 'UTF-8');
Validate Input: Sanitize and validate user input to ensure it follows the
expected format.
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
Use Content Security Policy (CSP): Restrict which content can be
loaded to reduce XSS risks.
header("Content-Security-Policy: default-src 'self'; script-src
‘self’ 5")5
39. What is the difference between crypt() and password_hash()?
-[Link]/php/php-intrview-questions-and-answers! 46132‘918125, 7:33 PM PHP Interview Questions and Answers-2025 - GocksforGeoks
crypt() password_hash()
General-purpose hash, not for Specifically for securely hashing
passwords specifically passwords
Supports multiple algorithms
Uses berypt (with automatic salting)
(eg, MDS, SHA-512)
Must handle manually Automatically generates a unique salt
Supports rehashing with
No built-in support
password_needs_rehash()
May use insecure algorithms Secure (berypt) with resistance to
(e.g., MDS, DES) brute-force attacks
40. How do you create and use an interface in PHP?
An interface in PHP defines a contract for classes that implement it. It
specifies methods that the implementing classes must define, but it
does not provide the method implementation itself.
* Define an Interface: Use the interface keyword to define an interface.
The methods declared inside the interface must be public.
interface Animal {
public function speak();
+ Implement the Interface: A class can implement an interface using
the implements keyword. The class must define all the methods
declared in the interface.
class Dog implements Animal {
public function speak() {
-[Link]/php/php-intrview-questions-and-answers! 1132‘9/8125, 7:33 PM PHP Interview Questions and Anewers-2025 - GooksforGeeks
echo "Woof!";
* Using the Interface: Create an object of the class that implements
the interface and call the method.
$dog = new Dog();
$dog->speak();
41. How to send an email using PHP?
In PHP, we can send an email using the built-in mail() function. Here's a
simple way to send an email:
Synatx
mail($to, $subject, $message, $headers);
© to: The recipient's email address
* $subject: The subject of the email,
+ $message: The body content of the email.
* $headers: Additional headers, like "From", "Reply-To", etc. (optional).
PHP Interview Questions for Advanced
42. What is dependency injection in PHP?
Dependency Injection (Dl) is a design pattern used to implement
Inversion of Control (loC), where an object's dependencies (other objects
it depends on) are provided to it rather than the object creating them
itself.
43. Explain the SOLID principles in PHP.
The SOLID principles are a set of five design principles that help
developers write better, more maintainable, and scalable object-oriented
-[Link]/php/php-intrview-questions-and-answers! 181329/1825, 7:33 PM PHP Intrviow Questions and Answers -2025 - GeektorGeoks
code. They are widely used in PHP development to improve code
readability, flexibility, and reusability.
Single Responsibility Principle (SRP) : A class should have only one
reason to change, meaning it should only have one job or
responsibility.
Open/Closed Principle (OCP) : A class should be open for extension
but closed for modification.
Liskov Substitution Principle (LSP) : Objects of a superclass should
be replaceable with objects of a subclass without affecting the
correctness of the program.
Interface Segregation Principle (ISP) ; A client should not be forced
to depend on interfaces it does not use.
Dependency Inversion Principle (DIP) : High-level modules should
not depend on low-level modules. Both should depend on
abstractions.
44. How do you optimize PHP applications for performance?
To optimize PHP applications for better performance, you can implement
several techniques to minimize resource usage and enhance execution
speed.
Use Opcode Caching (e.g., OPcache): Caching the compiled PHP
code in memory reduces the need for PHP to parse and compile
scripts on every request.
Optimize Database Queries: Inefficient database queries can slow
down the application.
Use Content Delivery Networks (CDNs): Offloading static content to
CDNs reduces server load and speeds up content delivery by caching
resources closer to users.
Enable Compression (e.g., GZIP): Compressing the output reduces
the size of HTML, CSS, and JavaScript files, which speeds up page
loading.
Cache Dynamic Content: Caching avoids repeated computations for
dynamic content, improving response time.
-[Link]/php/php-intrview-questions-and-answers! 9132anes, 793M PHP Iterviow Questions and Answors-2025-GeottorGeoks
* Use Asynchronous Operations: Offload non-critical tasks to avoid
blocking the main thread and improve application responsiveness.
* Profile and Benchmark Code: Identifying slow parts of the
application helps optimize performance.
45. What are middleware in PHP frameworks?
Middleware in PHP frameworks are components that sit between the
request and response cycle. They allow you to filter, modify, or handle
requests before they reach the application's core logic or after the
response is generated but before it is sent to the client.
Purpose: Middleware handles tasks like authentication, logging,
request validation, and modifying HTTP responses
Usage: They are executed in a specific order, with each middleware
passing control to the next until the final response is returned.
Example: In frameworks like Laravel, middleware can handle tasks
like ensuring the user is authenticated before accessing certain
routes.
46. What are the steps to create a new database using MySQL
and PHP?
The four main steps used to create a new MySQL database in PHP are
given below:
A connection establishment is done to the MySQL server using the
PHP script.
The connection is validated. If the connection is successful, then you
can write a sample query to verify.
Queries that create the database are input and later stored into a
string variable.
Then, the created queries will be executed one after the other
47. Write a function to reverse a string without using strrev().
o
function reverse($str) {
-[Link]/php/php-intrview-questions-and-answers! 20192‘1625, 7:3 PM PHP Interview Questions and Answers -2025 - GeekstorGeeks
$reversed = ""5
for ($i = strlen($str) - 15 $i >= 0; $i--) {
$reversed .= $str[$i];
}
return $reversed;
echo reverse("GeeksforGeeks");
>
Output
skeeGrofskeeG
* Initialize an empty string Sreversed.
* Loop through the input string from last character to first.
* Append each character to Sreversed.
* Return the reversed string.
48. How would you remove duplicate values from an array in
PHP?
Output
Array
(
[2] => 4
[1] => 2
[2] => 3
[3] => 4
-[Link]/php/php-intrview-questions-and-answers! 292sy1825, 739M PHP Itrew Questions and Answors-2025- GekstorSeoks
[4] => 5
)
* array_unique(Sarr): Removes duplicate values from the array Sarr.
* array_values(): Re-indexes the array to ensure the keys are in
numerical order starting from 0.
49. Implement a function to check if a string is a palindrome
@
function isPalindrome($str) {
return strtolower($str) =:
strtolower(strrev($str))5
echo isPalindrome("madam") ? "Palindrome” : "Not a Palindrome";
>
Output
Palindrome
* Remove non-alphanumeric characters and convert to lowercase.
* Reverse the string and compare with the original.
* Returns True if the string is a palindrome, otherwise False.
50. Write a PHP function to find the second largest number in an
array.
Output
-[Link]/php/php-intrview-questions-and-answers! 22192‘9/8125, 7:33 PM PHP Interview Questions and Anewers-2025 - GooksforGeeks
45
* array_unique($arr): Removes duplicate values from the array.
* rsort(Sarr): Sorts the array in descending order.
* $arr[1] 7? null: Returns the second element (second largest number).
If the array has less than two unique elements, it returns null.
51. Write a function to check whether a number is prime.
o
function isPrime($num) {
if ($num < 2) return false;
for ($i = 23 $i <= sqrt($num); $it+) {
if ($num % $i == @) return false;
y
return true;
echo isPrime(29) ? "Prime" : "Not Prime”;
»>
Output
Prime
* if ($num < 2): If the number is less than 2, it returns false since prime
numbers are greater than 1.
for ($i = 2; $i <= sqrt($num); $i++): Loops through numbers from 2
to the square root of the input number.
if (Snum % $i == 0): If the number is divisible by any number in the
loop, it's not prime, so it returns false.
return true: If no divisor is found, the number is prime, so it returns
true.
52. How would you implement a recursive function to calculate
the factorial of a number?
oO
function factorial($n) {
-[Link]/php/php-intrview-questions-and-answers! 2392‘918125, 7:33 PM PHP Interview Questions and Anewers-2025 - GooksforGeeks
return ($n <= 1) 2.1: $n * factorial($n - 1);
echo factorial (5);
»
Output
120
Base case ($n <= 1): If $nis 1 or less, return 1 (since the factorial of 0
and Lis 1).
Recursive case: For values greater than 1, it calls factorial($n - 1) and
multiplies it by $n, which keeps reducing until it reaches the base
case.
53. Write a function to sort an array without using sort().
$arr[$j + 1]) {
list($arr[$j], $arr[$j + 1]) = [$arr[$j + 1],
$arr[$5]]5
}
+
return $arr3
$nums = [64, 34, 25, 12, 22, 11, 90];
print_r(bubbleSort ($nums));
>
Output
Array
(
[2] => 11
-[Link]/php/php-intrview-questions-and-answers! 2a‘9/8125, 7:33 PM PHP Interview Questions and Anewers-2025 - GooksforGeeks
[1] => 12
[2] => 22
[3] => 25
[4] => 34
[5] => 64
[6] => 98
)
* Outer loop ($i): Runs through the array multiple times, each time
excluding the last sorted element.
* Inner loop ($j): Compares adjacent elements in the array and swaps
them if they are in the wrong order ($arr[$j] > Sarr[$j + 1]).
* Swap: Uses list() to swap the elements without needing a temporary
variable.
54. How can you merge two sorted arrays into a single sorted
array in PHP?
1
[1] => 3
2] => 5
[LB] > 2
[4] > 4
[5] => 6
)
-[Link]/php/php-intrview-questions-and-answers!‘1625, 7:3 PM PHP Interview Questions and Answers -2025 - GeekstorGeeks
* array_merge($arr1, $arr2): This built-in PHP function merges the
two input arrays Sarr1 and $arr2 into a single array.
* The function does not guarantee that the merged array will remain
sorted; it simply combines the arrays as they are.
55. Write a function to generate the Fibonacci series up ton
terms.
Output
Array
(
[2] => @
[a] => 4
[2] > 4
[3] => 2
[4] => 3
[5] => 5
[6] => 8
[7] => 13
[8] => 21
[9] => 34
)
* Initial Array: The function starts with an array $fib = [0, 1], which
represents the first two Fibonacci numbers.
* Loop: The loop starts at index 2 and calculates each subsequent
Fibonacci number as the sum of the previous two (Sfib{Si] = Sfib[$i -
-[Link]/php/php-intrview-questions-and-answers!anes, 793M PHP Iterviow Questions and Answors-2025-GeottorGeoks
1] + Sfib[Si - 2)).
* Return: It returns the complete Fibonacci sequence up to the nth
term.
56. How do you find the most frequent element in an array?
check()) return redirect('/login');
return $next($request);
64. What is the difference between Laravel and Symfony?
Laravel Symfony
Easier to learn More complex
Moderate Faster with optimized settings
Rapid development _ Enterprise applications
65. Explain the Repository Pattern in PHP.
The Repository Pattern separates business logic from database queries
class UserRepository { x bo
public function getAllUsers() {
return User::al1()5
Top 10 Commonly asked PHP Interview Questions
What is PHP?
Whats the difference between echo and print in PHP?
What are the different types of variables in PHP?
What are superglobals in PHP?
1.
2.
3.
4,
5. What is the difference between == and in PHP?
6.
7.
8.
What are sessions and cookies in PHP?
What are the advantages of using PHP?
How does PHP handle error handling?
9. What is a PHP function?
-[Link]/php/php-intrview-questions-and-answers! 30132‘9/8125, 7:33 PM PHP Interview Questions and Anewers-2025 - GooksforGeeks
10. What is the difference between include() and require() in PHP?
oe
PHP a
a
INTERVIEW
uestions and Answers]
Comment || Moreinfo
LD
(conmrenne ream]
OG GesksforGeeks
Corporate & Communications Address:
4-143, 7th Floor, Sovereign Corporate
Tower, Sector- 136, Noida, Uttar Pradesh
(201305)
Registered Address:
K 061, Tower k, Gulshan Vivante
Apartment, Sector 137, Noida, Gautam
Buddh Nagar, Uttar Pradesh, 201305,
Advertise with us
Company Explore
-[Link]/php/php-intrview-questions-and-answers! 31132‘9/8125, 7:33 PM PHP Interview Questions and Anewers-2025 - GooksforGeeks
About Us Porp
Legal Job-A-Thon
Privacy Policy Connect
Careers Community
Contact Us Blogs
Corporate Solution Nation Skill Up
Campus Training Program
Tutorials Courses
Programming Languages IBM Certification
DSA DSAand Placements
Web Technology Web Development
Al, ML & Data Science Data Science
Devops Programming Languages
cS Core Subjects DevOps & Cloud
Gate
Interview Preparation
cate. Trending Technologies
‘School Subjects
Software and Tools
Offline Centers Preparation Corner
Noida Aptitude
Bengaluru Puzzles
Pune i660
Hyderabad DsA360
Patna system Design
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
-[Link]/php/php-intrview-questions-and-answers!
32132
Das könnte Ihnen auch gefallen