0% found this document useful (0 votes)
12 views31 pages

PHP Quest

notes

Uploaded by

Sonu zehen001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views31 pages

PHP Quest

notes

Uploaded by

Sonu zehen001
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Here’s a list of common PHP interview ques ons, covering a range of topics from basics to advanced

concepts:

### **Basic PHP Interview Ques ons:**

1. **What is PHP?**

- PHP stands for Hypertext Preprocessor. It is a server-side scrip ng language primarily used for web
development. It is embedded in HTML and used to create dynamic web pages.

2. **What are the key differences between `echo` and `print` in PHP?**

- Both `echo` and `print` are used to output data, but:

- `echo` can take mul ple parameters, while `print` can only take one.

- `print` always returns `1`, which makes it suitable for use in expressions, while `echo` doesn’t return
any value.

3. **Explain the difference between `include` and `require` in PHP.**

- `include`: Includes and evaluates the specified file. If the file is not found, a warning is issued, but the
script will con nue.

- `require`: Similar to `include`, but if the file is not found, a fatal error is thrown, and the script will
stop.

4. **What are PHP variables and how do you define them?**

- Variables in PHP are denoted with a dollar sign (`$`) followed by the variable name. They are
dynamically typed and do not require explicit type defini on.

- Example: `$var = 5;`

5. **What are the types of errors in PHP?**

- **Syntax errors**: Errors in code syntax.

- **Run me errors**: Errors that occur during the execu on of the script.

- **Logical errors**: Errors in logic that cause unintended behavior but do not break the script.

- **PHP error levels**: E_WARNING, E_NOTICE, E_ERROR, etc.


6. **What are superglobals in PHP?**

- Superglobals are built-in global arrays in PHP that are always accessible, regardless of scope. Examples
include `$_POST`, `$_GET`, `$_SESSION`, `$_COOKIE`, `$_REQUEST`, `$_SERVER`, `$_FILES`, and `$_ENV`.

7. **What is the difference between `==` and `===` in PHP?**

- `==` (loose comparison) checks if the values are equal, but it doesn’t check the data type.

- `===` (strict comparison) checks both value and data type.

---

### **Intermediate PHP Interview Ques ons:**

8. **Explain the concept of sessions and cookies in PHP.**

- **Sessions**: Used to store data across mul ple pages for a single user session. Session data is stored
on the server, and the session is iden fied by a unique session ID (usually stored in a cookie).

- **Cookies**: Small pieces of data stored on the client-side (in the user’s browser). Cookies have an
expira on date, while session data lasts only for the dura on of the session.

9. **What is an associa ve array in PHP?**

- An associa ve array is an array where each key is assigned to a specific value, and the keys are
typically strings, rather than numeric indices.

- Example: `$arr = ['name' => 'John', 'age' => 30];`

10. **What is the difference between `POST` and `GET` methods in PHP?**

- **GET**: Data is sent via the URL and is visible to the user. It is limited to a small amount of data and
is typically used for retrieving data.

- **POST**: Data is sent through the HTTP request body and is not visible in the URL. It can handle
larger amounts of data and is used for submi ng data (e.g., form submissions).

11. **How do you handle form submission in PHP?**


- PHP handles form data through the `$_GET` or `$_POST` superglobals depending on the method
specified in the form.

- Example:

```php

if ($_SERVER["REQUEST_METHOD"] == "POST") {

$name = $_POST["name"];

```

12. **What is a PHP namespace?**

- Namespaces are a way of grouping related classes, interfaces, func ons, and constants together to
avoid name conflicts. You define a namespace using the `namespace` keyword.

```php

namespace MyApp\Models;

class User {}

```

13. **What are the different types of loops in PHP?**

- **for loop**: Loops for a specific number of itera ons.

- **while loop**: Loops while a condi on is true.

- **do-while loop**: Loops at least once, then con nues as long as a condi on is true.

- **foreach loop**: Iterates through an array.

---

### **Advanced PHP Interview Ques ons:**

14. **What are traits in PHP?**


- Traits are a mechanism for code reuse in PHP. They allow you to include methods in mul ple classes,
overcoming the limita ons of single inheritance in PHP.

```php

trait Logger {

public func on log($message) {

echo $message;

```

15. **Explain autoloading in PHP.**

- Autoloading allows PHP to automa cally load classes when they are needed. This eliminates the
need for explicit `include` or `require` statements.

- Example using `spl_autoload_register()`:

```php

func on my_autoloader($class) {

include 'classes/' . $class . '.[Link]';

spl_autoload_register('my_autoloader');

```

16. **What is PDO in PHP, and how does it work?**

- **PDO** (PHP Data Objects) is a database access layer that provides a consistent interface for
interac ng with various databases (e.g., MySQL, PostgreSQL). It supports prepared statements and helps
prevent SQL injec on.

Example:

```php

$pdo = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');


$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');

$stmt->execute(['id' => $id]);

```

17. **Explain the difference between `mysqli` and `PDO`.**

- `mysqli` (MySQL Improved) is specific to MySQL databases and provides both procedural and object-
oriented interfaces.

- `PDO` is a database abstrac on layer that supports mul ple database types. It uses only the object-
oriented approach.

18. **What is the purpose of `__construct()` and `__destruct()` methods in PHP?**

- `__construct()`: A magic method called when a new object is instan ated. It is typically used for
object ini aliza on.

- `__destruct()`: A magic method called when an object is destroyed or goes out of scope. It is used to
clean up resources.

19. **What is the difference between `public`, `private`, and `protected` in PHP?**

- `public`: The property or method is accessible from anywhere.

- `private`: The property or method is only accessible within the same class.

- `protected`: The property or method is accessible within the same class and by derived (child)
classes.

20. **How does PHP handle memory management?**

- PHP uses a garbage collector (GC) to automa cally clean up unused objects and variables. Memory
management is primarily handled by reference coun ng, and cyclic references are handled by the
garbage collector.

---

### **Design Pa erns and Best Prac ces:**


21. **What is the Singleton pa ern, and how can it be implemented in PHP?**

- The Singleton pa ern ensures that a class has only one instance and provides a global point of access
to that instance.

- Example:

```php

class Singleton {

private sta c $instance = null;

private func on __construct() {}

public sta c func on getInstance() {

if (self::$instance === null) {

self::$instance = new Singleton();

return self::$instance;

```

22. **What is MVC (Model-View-Controller) architecture?**

- MVC is a design pa ern used to separate an applica on into three interconnected components:

- **Model**: Represents the data or business logic.

- **View**: Represents the presenta on or user interface.

- **Controller**: Handles user input and updates the model and view accordingly.

23. **What are some best prac ces in PHP development?**

- Use meaningful variable and func on names.

- Avoid using global variables.

- Sani ze and validate user input to prevent security risks like SQL injec on.
- Follow the DRY (Don’t Repeat Yourself) principle.

- Use prepared statements for database interac ons to avoid SQL injec on.

- Use Composer for dependency management.

- Write unit tests to ensure code quality.

---

### **Addi onal PHP Concepts:**

24. **Explain Dependency Injec on in PHP.**

- Dependency Injec on (DI) is a design pa ern used to decouple classes by injec ng their
dependencies from the outside. This improves testability and maintainability.

25. **What is Composer in PHP?**

- Composer is a dependency management tool for PHP. It allows you to manage external libraries and
packages, and autoload them efficiently in your project.

Here are some **Object-Oriented Programming (OOP)** ques ons in PHP that are commonly asked
during interviews. These ques ons cover the core principles of OOP, such as classes, objects, inheritance,
polymorphism, encapsula on, and abstrac on.

### **Basic OOP in PHP Interview Ques ons:**

1. **What is Object-Oriented Programming (OOP)?**

- OOP is a programming paradigm based on the concept of objects. In PHP, OOP allows developers to
structure code in a way that models real-world en es using classes and objects. The core principles of
OOP are:
- **Encapsula on**: Bundling the data (proper es) and the methods that operate on the data within
a class.

- **Inheritance**: A mechanism to create a new class from an exis ng class.

- **Polymorphism**: The ability to treat objects of different types as objects of a common super type.

- **Abstrac on**: Hiding the complex implementa on details and exposing only essen al parts of an
object.

2. **What is a class in PHP?**

- A class is a blueprint or template for crea ng objects. It defines proper es (variables) and methods
(func ons) that the objects created from the class will have.

```php

class Car {

public $color;

public $model;

public func on startEngine() {

echo "Engine started!";

```

3. **What is an object in PHP?**

- An object is an instance of a class. It is created using the `new` keyword. Objects hold the state and
behavior defined by the class.

```php

$myCar = new Car();

$myCar->color = "Red";

$myCar->startEngine();
```

4. **What is the difference between a class and an object in PHP?**

- **Class**: A blueprint for crea ng objects, containing proper es and methods.

- **Object**: An instance of a class with actual values and the ability to invoke the class’s methods.

5. **What are visibility modifiers in PHP?**

- Visibility modifiers define the accessibility of class proper es and methods. They are:

- **public**: Accessible from anywhere (inside and outside the class).

- **protected**: Accessible within the class and by subclasses.

- **private**: Accessible only within the class itself.

Example:

```php

class User {

public $name;

private $password;

public func on __construct($name, $password) {

$this->name = $name;

$this->password = $password;

```

---

### **Intermediate OOP in PHP Interview Ques ons:**


6. **What is inheritance in PHP?**

- Inheritance is a mechanism that allows one class (child class) to inherit proper es and methods from
another class (parent class). This helps in reusing code and establishing rela onships between classes.

Example:

```php

class Animal {

public $name;

public func on speak() {

echo "Animal speaking!";

class Dog extends Animal {

public func on speak() {

echo "Woof! Woof!";

$dog = new Dog();

$dog->speak(); // Output: Woof! Woof!

```

7. **What is polymorphism in PHP?**

- Polymorphism allows objects of different classes to be treated as objects of a common parent class. In
PHP, polymorphism is achieved through method overriding and interfaces.

Example (method overriding):


```php

class Shape {

public func on draw() {

echo "Drawing Shape";

class Circle extends Shape {

public func on draw() {

echo "Drawing Circle";

$shape = new Shape();

$circle = new Circle();

$shape->draw(); // Output: Drawing Shape

$circle->draw(); // Output: Drawing Circle

```

8. **What is method overloading in PHP?**

- PHP doesn’t support true method overloading (like Java or C++). However, you can simulate method
overloading by using the `__call()` magic method, which allows you to call methods that do not exist or
are not visible.

Example:

```php

class Test {

public func on __call($method, $args) {

echo "Called method: $method with arguments: " . implode(", ", $args);
}

$obj = new Test();

$obj->nonExistentMethod("param1", "param2"); // Output: Called method: nonExistentMethod with


arguments: param1, param2

```

9. **What is the difference between `extends` and `implements` in PHP?**

- **`extends`**: Used to inherit from a parent class (single inheritance). A class can extend only one
class.

- **`implements`**: Used to implement an interface. A class can implement mul ple interfaces.

Example:

```php

interface Shape {

public func on draw();

class Circle implements Shape {

public func on draw() {

echo "Drawing Circle";

```

10. **What is an interface in PHP?**

- An interface defines a contract of methods that a class must implement. Interfaces only contain
method declara ons (without body) and cannot have proper es.
Example:

```php

interface Shape {

public func on draw();

class Rectangle implements Shape {

public func on draw() {

echo "Drawing Rectangle";

```

11. **What is an abstract class in PHP?**

- An abstract class cannot be instan ated directly and may contain abstract methods (methods
without implementa on). Child classes must implement these abstract methods.

Example:

```php

abstract class Animal {

abstract public func on sound();

public func on sleep() {

echo "Sleeping...";

class Dog extends Animal {

public func on sound() {


echo "Bark!";

```

12. **Can you explain the use of the `__construct()` and `__destruct()` methods in PHP?**

- **`__construct()`**: This is a magic method that is automa cally called when an object is created. It
is used to ini alize object proper es.

- **`__destruct()`**: This magic method is automa cally called when an object is destroyed or when
the script ends. It is typically used to clean up resources (e.g., closing database connec ons).

Example:

```php

class MyClass {

public func on __construct() {

echo "Object Created!";

public func on __destruct() {

echo "Object Destroyed!";

$obj = new MyClass(); // Output: Object Created!

unset($obj); // Output: Object Destroyed!

```

---
### **Advanced OOP in PHP Interview Ques ons:**

13. **What is a trait in PHP, and why is it used?**

- A trait is a mechanism for code reuse in PHP. It allows you to share methods across mul ple classes
without requiring inheritance. A class can use mul ple traits.

Example:

```php

trait Logger {

public func on log($message) {

echo "Log: $message";

class User {

use Logger;

$user = new User();

$user->log("User logged in"); // Output: Log: User logged in

```

14. **What is dependency injec on in PHP?**

- Dependency Injec on (DI) is a design pa ern where a class’s dependencies (e.g., other objects) are
injected into it, rather than the class crea ng them itself. This improves the modularity and testability of
the code.

Example (simple DI):

```php

class Database {
public func on connect() {

return "Connec ng to database";

class User {

private $db;

// Injec ng dependency via constructor

public func on __construct(Database $db) {

$this->db = $db;

public func on getUserData() {

return $this->db->connect();

$db = new Database();

$user = new User($db);

echo $user->getUserData(); // Output: Connec ng to database

```

15. **What is the `__callSta c()` method in PHP?**

- The `__callSta c()` magic method is called when invoking inaccessible methods sta cally. This
method is useful for handling dynamic sta c method calls.

Example:

```php
class MyClass {

public sta c func on __callSta c($method, $args) {

echo "Called sta c method: $method with arguments: " . implode(", ", $args);

MyClass::dynamicMethod("arg1", "arg2"); // Output: Called sta c method: dynamicMethod with


arguments: arg1, arg2

```

16. **Explain the SOLID principles in the context of PHP.**

- SOLID is a set of principles for object-oriented design:

1. **S** - Single Responsibility Principle (SRP): A class should have only one reason to change.

2. **O** - Open/Closed Principle (OCP): A class should be open for extension, but closed for
modifica on.

3. **L** - Liskov Subs tu on Principle (LSP): Objects of a superclass should be replaceable with
objects of a subclass without affec ng the program.

4. **I** - Interface Segrega on Principle (ISP): Clients should not

be forced to depend on methods they do not use.

5. **D** - Dependency Inversion Principle (DIP): High-level modules should not depend on low-level
modules. Both should depend on abstrac ons.

Here are some **MySQL interview ques ons** that cover various aspects of MySQL, from basic
concepts to more advanced topics like performance op miza on and database design. These ques ons
will help you prepare for a range of interviews where MySQL is used as the database management
system.
---

### **Basic MySQL Interview Ques ons:**

1. **What is MySQL?**

- MySQL is an open-source rela onal database management system (RDBMS) that uses Structured
Query Language (SQL) for managing and manipula ng rela onal databases. It is widely used for web
applica ons and is known for its speed, reliability, and ease of use.

2. **What are the different types of joins in MySQL?**

- The different types of joins in MySQL are:

- **INNER JOIN**: Returns only the rows that have matching values in both tables.

- **LEFT JOIN (or LEFT OUTER JOIN)**: Returns all rows from the le table, and matching rows from
the right table. If no match, returns `NULL` for the right table's columns.

- **RIGHT JOIN (or RIGHT OUTER JOIN)**: Similar to LEFT JOIN but returns all rows from the right
table.

- **FULL JOIN (or FULL OUTER JOIN)**: Returns all rows when there is a match in either the le or
right table. (Note: MySQL doesn't support FULL JOIN directly, but it can be simulated using `UNION` of
`LEFT JOIN` and `RIGHT JOIN`.)

3. **What is a primary key in MySQL?**

- A **primary key** is a field (or a combina on of fields) that uniquely iden fies each row in a table. A
primary key must contain unique values and cannot contain `NULL` values.

4. **What is a foreign key in MySQL?**

- A **foreign key** is a field (or combina on of fields) that creates a link between two tables. It is used
to enforce referen al integrity by ensuring that the value in the foreign key column matches a primary
key value in another table.

5. **What are the differences between `CHAR` and `VARCHAR`?**

- **CHAR**: A fixed-length string. If the string is shorter than the defined length, it will be padded with
spaces.
- **VARCHAR**: A variable-length string. It uses only as much space as needed to store the string.

6. **What is an index in MySQL?**

- An index is a data structure that improves the speed of data retrieval opera ons on a table. It can be
created on one or more columns and allows for faster query execu on, par cularly on large datasets.

7. **What is normaliza on in a database?**

- **Normaliza on** is the process of organizing data in a database to reduce redundancy and
dependency. The goal is to divide large tables into smaller, related tables and establish rela onships
between them. The process usually involves applying a set of **normal forms** (1NF, 2NF, 3NF, etc.).

8. **What is denormaliza on, and why is it used?**

- **Denormaliza on** is the process of combining tables or adding redundancy back into the database
to op mize read performance. It is o en used when performance issues arise in highly normalized
databases, par cularly for read-heavy workloads.

---

### **Intermediate MySQL Interview Ques ons:**

9. **What is a transac on in MySQL?**

- A **transac on** is a sequence of one or more SQL opera ons that are executed as a single unit of
work. Transac ons ensure data integrity by following the **ACID** proper es (Atomicity, Consistency,
Isola on, Durability). In MySQL, transac ons are supported by the **InnoDB** storage engine.

- Example:

```sql

START TRANSACTION;

INSERT INTO accounts (balance) VALUES (1000);

UPDATE accounts SET balance = balance - 100 WHERE account_id = 1;

COMMIT;
```

10. **What is the difference between `DELETE`, `TRUNCATE`, and `DROP`?**

- **DELETE**: Deletes rows from a table, and it can be rolled back if wrapped in a transac on. It can
have a `WHERE` clause to filter rows.

- **TRUNCATE**: Removes all rows from a table but does not log individual row dele ons. It is faster
than `DELETE` but cannot be rolled back in most cases.

- **DROP**: Deletes the table structure itself from the database. Once dropped, the table and all its
data are permanently removed.

11. **What are the differences between `UNION` and `UNION ALL`?**

- **UNION**: Combines the results of two or more queries and removes duplicate rows.

- **UNION ALL**: Combines the results of two or more queries without removing duplicates, which
makes it faster than `UNION`.

12. **What is the `GROUP BY` clause in MySQL?**

- The `GROUP BY` clause is used to group rows that have the same values in specified columns into
summary rows. It is o en used with aggregate func ons like `COUNT()`, `SUM()`, `AVG()`, `MAX()`, and
`MIN()`.

Example:

```sql

SELECT department, COUNT(*) FROM employees GROUP BY department;

```

13. **What are aggregate func ons in MySQL?**

- Aggregate func ons perform a calcula on on a set of values and return a single value. Common
aggregate func ons in MySQL include:

- `COUNT()`

- `SUM()`

- `AVG()`
- `MIN()`

- `MAX()`

14. **What is the purpose of the `HAVING` clause in MySQL?**

- The `HAVING` clause is used to filter results a er the `GROUP BY` opera on. It is similar to the
`WHERE` clause, but `WHERE` is used for row filtering before grouping, while `HAVING` is used for
filtering groups a er the `GROUP BY`.

Example:

```sql

SELECT department, COUNT(*) FROM employees GROUP BY department HAVING COUNT(*) > 5;

```

15. **What is a subquery in MySQL?**

- A **subquery** is a query embedded within another query. It is typically used in `SELECT`, `INSERT`,
`UPDATE`, or `DELETE` statements and can return a single value or a result set.

Example:

```sql

SELECT name FROM employees WHERE department_id = (SELECT id FROM departments WHERE name
= 'Sales');

```

---

### **Advanced MySQL Interview Ques ons:**

16. **What is an `EXPLAIN` statement in MySQL?**

- The `EXPLAIN` statement is used to analyze and op mize queries by showing the query execu on
plan. It provides details on how MySQL executes a query, including the order of table joins, index usage,
and more.
Example:

```sql

EXPLAIN SELECT * FROM employees WHERE department_id = 1;

```

17. **How would you op mize a slow-running query in MySQL?**

- Some common ways to op mize a slow-running query include:

- Use **indexes** on columns that are frequently queried or used in `JOIN`, `WHERE`, or `ORDER BY`
clauses.

- Avoid `SELECT *` and only retrieve necessary columns.

- Use **EXPLAIN** to analyze the query execu on plan.

- Op mize `JOIN` opera ons by ensuring they are efficient.

- Use query caching if appropriate.

- Normalize large data sets where necessary to improve efficiency.

- Break down complex queries into simpler ones.

18. **What is MySQL replica on?**

- **Replica on** in MySQL allows data from one database server (master) to be copied to one or
more database servers (slaves). Replica on is commonly used for high availability, load balancing, and
backup purposes.

19. **What is the difference between InnoDB and MyISAM in MySQL?**

- **InnoDB**:

- Supports transac ons and foreign key constraints.

- Provides be er support for high concurrency and is the default storage engine in MySQL.

- Uses row-level locking for be er performance on write-heavy opera ons.

- **MyISAM**:

- Does not support transac ons or foreign key constraints.

- Faster for read-heavy applica ons.


- Uses table-level locking, which can cause performance issues with high concurrent writes.

20. **How would you implement full-text search in MySQL?**

- Full-text search allows searching for words or phrases within a text column. To use full-text search in
MySQL:

- Create a full-text index on the text columns.

- Use the `MATCH()` and `AGAINST()` func ons to perform searches.

Example:

```sql

CREATE TABLE ar cles (id INT, tle VARCHAR(255), content TEXT, FULLTEXT ( tle, content));

SELECT * FROM ar cles WHERE MATCH( tle, content) AGAINST('search term');

```

21. **What are stored procedures and func ons in MySQL?**

- **Stored procedures** are precompiled collec ons of SQL statements that can be executed as a unit.
They can accept parameters and return results.

- **Func ons** are similar to stored procedures but must return a single value and can be used within
queries.

Example (stored procedure):

```sql

DELIMITER //

CREATE PROCEDURE GetEmployeeDetails(IN emp_id INT)

BEGIN

SELECT * FROM employees WHERE id = emp_id;

END //

DELIMITER ;

```
22. **What is the difference between `TRUNCATE` and `DELETE` from a performance perspec ve?**

- **TRUNCATE** is faster than `DELETE` because it doesn’t log individual row dele ons and does not
scan the

table for foreign key constraints. It removes all rows in a table without triggering individual row-based
opera ons.

- **DELETE** logs each row dele on and is slower than `TRUNCATE` for large datasets.

In PHP, there are many **predefined func ons** that can be used for manipula ng arrays. These
func ons allow you to perform a wide variety of opera ons on arrays, such as sor ng, filtering,
searching, and modifying array elements. Below is a list of some of the most commonly used PHP array
func ons:

### **1. Array Crea on and Manipula on Func ons**

- **`array()`**: Creates an array.

```php

$arr = array(1, 2, 3, 4);

```

- **`array_merge()`**: Merges two or more arrays into one.

```php

$array1 = array(1, 2);

$array2 = array(3, 4);

$merged = array_merge($array1, $array2); // [1, 2, 3, 4]

```
- **`array_merge_recursive()`**: Merges two or more arrays recursively, merging values of the same
keys.

```php

$array1 = array("a" => "apple", "b" => "banana");

$array2 = array("b" => "blueberry", "c" => "cherry");

$merged = array_merge_recursive($array1, $array2);

// Array ( [a] => apple [b] => Array ( [0] => banana [1] => blueberry ) [c] => cherry )

```

- **`array_slice()`**: Extracts a por on of an array.

```php

$arr = array(1, 2, 3, 4, 5);

$slice = array_slice($arr, 2, 2); // [3, 4]

```

- **`array_splice()`**: Removes a por on of an array and op onally replaces it with new elements.

```php

$arr = array(1, 2, 3, 4, 5);

array_splice($arr, 2, 2, array(6, 7)); // [1, 2, 6, 7, 5]

```

- **`array_diff()`**: Computes the difference of arrays (elements present in the first array but not in any
of the others).

```php

$arr1 = array(1, 2, 3);

$arr2 = array(2, 3, 4);

$diff = array_diff($arr1, $arr2); // [1]

```
- **`array_diff_assoc()`**: Computes the difference of arrays with keys and values.

```php

$arr1 = array("a" => "apple", "b" => "banana");

$arr2 = array("a" => "apple", "b" => "orange");

$diff_assoc = array_diff_assoc($arr1, $arr2); // Array ( [b] => banana )

```

- **`array_keys()`**: Returns all the keys or a subset of the keys from an array.

```php

$arr = array("a" => "apple", "b" => "banana", "c" => "cherry");

$keys = array_keys($arr); // ["a", "b", "c"]

```

- **`array_values()`**: Returns all the values from an array.

```php

$arr = array("a" => "apple", "b" => "banana");

$values = array_values($arr); // ["apple", "banana"]

```

- **`array_key_exists()`**: Checks if a given key exists in an array.

```php

$arr = array("a" => "apple", "b" => "banana");

$exists = array_key_exists("a", $arr); // true

```

---

### **2. Sor ng Func ons**


- **`sort()`**: Sorts an array in ascending order (by value).

```php

$arr = array(3, 1, 2);

sort($arr); // [1, 2, 3]

```

- **`rsort()`**: Sorts an array in descending order (by value).

```php

$arr = array(3, 1, 2);

rsort($arr); // [3, 2, 1]

```

- **`asort()`**: Sorts an array in ascending order, maintaining key-value rela onships.

```php

$arr = array("a" => 3, "b" => 1, "c" => 2);

asort($arr); // ["b" => 1, "c" => 2, "a" => 3]

```

- **`ksort()`**: Sorts an array by keys in ascending order.

```php

$arr = array("b" => 2, "a" => 1, "c" => 3);

ksort($arr); // ["a" => 1, "b" => 2, "c" => 3]

```

- **`usort()`**: Sorts an array by values using a user-defined comparison func on.

```php

$arr = array(3, 1, 2);

usort($arr, func on($a, $b) { return $a - $b; }); // [1, 2, 3]

```
- **`uasort()`**: Sorts an array by values while maintaining key-value associa ons using a custom
comparison func on.

```php

$arr = array("a" => 3, "b" => 1, "c" => 2);

uasort($arr, func on($a, $b) { return $a - $b; }); // ["b" => 1, "c" => 2, "a" => 3]

```

- **`uksort()`**: Sorts an array by keys using a custom comparison func on.

```php

$arr = array("b" => 2, "a" => 1, "c" => 3);

uksort($arr, func on($a, $b) { return strcmp($a, $b); }); // ["a" => 1, "b" => 2, "c" => 3]

```

---

### **3. Searching Func ons**

- **`in_array()`**: Checks if a value exists in an array.

```php

$arr = array(1, 2, 3);

$exists = in_array(2, $arr); // true

```

- **`array_search()`**: Searches for a value in an array and returns the corresponding key.

```php

$arr = array("a" => "apple", "b" => "banana");

$key = array_search("banana", $arr); // "b"

```
- **`array_filter()`**: Filters elements of an array using a callback func on.

```php

$arr = array(1, 2, 3, 4, 5);

$filtered = array_filter($arr, func on($value) { return $value % 2 == 0; }); // [2, 4]

```

- **`array_map()`**: Applies a callback func on to the elements of an array.

```php

$arr = array(1, 2, 3);

$mapped = array_map(func on($value) { return $value * 2; }, $arr); // [2, 4, 6]

```

- **`array_reduce()`**: Itera vely reduces the array to a single value using a callback func on.

```php

$arr = array(1, 2, 3, 4);

$sum = array_reduce($arr, func on($carry, $item) { return $carry + $item; }, 0); // 10

```

---

### **4. Array Informa on Func ons**

- **`count()`**: Returns the number of elements in an array.

```php

$arr = array(1, 2, 3);

$count = count($arr); // 3

```
- **`array_sum()`**: Returns the sum of all elements in an array.

```php

$arr = array(1, 2, 3);

$sum = array_sum($arr); // 6

```

- **`array_product()`**: Returns the product of all elements in an array.

```php

$arr = array(2, 3, 4);

$product = array_product($arr); // 24

```

- **`array_rand()`**: Picks one or more random keys from an array.

```php

$arr = array(1, 2, 3, 4, 5);

$randomKey = array_rand($arr); // Random key, e.g., 2

```

- **`array_reverse()`**: Reverses the order of elements in an array.

```php

$arr = array(1, 2, 3);

$reversed = array_reverse($arr); // [3, 2, 1]

```

---

### **5. Array Sor ng and Shuffling**

- **`shuffle()`**: Randomly shuffles the elements of an array.


```php

$arr = array(1, 2, 3, 4, 5);

shuffle($arr); // Random order

```

- **`array_flip()`**: Flips keys and values of an array.

```php

$arr = array("a" => 1, "b" => 2);

$flipped = array_flip($arr); // [1 => "a", 2 => "b"]

```

You might also like