PHP Array: Theory and Examples
1. Arrays in PHP: Full Detail
An array is a data structure that allows you to store multiple values in a single variable. PHP arrays
can store different types of data and are categorized into three types:
1. Indexed Arrays
2. Associative Arrays
3. Multidimensional Arrays
---
### 1. Indexed Arrays
Indexed arrays store values with numeric indices starting from 0. These arrays are useful when you
need a simple list of elements.
#### Creating an Indexed Array
```php
$fruits = array("Apple", "Banana", "Orange", "Grapes");
```
#### Accessing Array Elements
```php
echo $fruits[0]; // Output: Apple
echo $fruits[1]; // Output: Banana
```
#### Modifying an Indexed Array
```php
$fruits[1] = "Mango"; // Changes "Banana" to "Mango"
echo $fruits[1]; // Output: Mango
```
#### Adding Elements to Indexed Array
```php
$fruits[] = "Pineapple";
```
---
### 2. Associative Arrays
Associative arrays store values using custom keys, which can be strings or numbers. This type of
array is useful when you want to associate a value with a descriptive name.
#### Creating an Associative Array
```php
$person = array("name" => "John", "age" => 30, "city" => "New York");
```
#### Accessing Values Using Keys
```php
echo $person["name"]; // Output: John
echo $person["age"]; // Output: 30
```
#### Modifying Associative Arrays
```php
$person["age"] = 31;
echo $person["age"]; // Output: 31
```
#### Adding Elements to Associative Array
```php
$person["email"] = "[email protected]";
```
---
### 3. Multidimensional Arrays
Multidimensional arrays store arrays within arrays, making them ideal for more complex data
structures like tables or matrices.
#### Creating a Multidimensional Array
```php
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
```
#### Accessing Multidimensional Array Elements
```php
echo $matrix[0][0]; // Output: 1
echo $matrix[1][2]; // Output: 6
```
#### Iterating Over a Multidimensional Array
```php
foreach ($matrix as $row) {
foreach ($row as $value) {
echo $value . " ";
echo "<br>";
```
#### Adding Elements to a Multidimensional Array
```php
$matrix[] = array(10, 11, 12);
```
---
### Common Array Functions in PHP
1. `count($array)`: Returns the number of elements in an array.
2. `array_push($array, $value)`: Adds elements to the end of the array.
3. `array_pop($array)`: Removes the last element from an array.
4. `in_array($value, $array)`: Checks if a value exists in an array.
5. `array_merge($array1, $array2)`: Merges two arrays.
---
Conclusion:
Arrays are an essential part of PHP programming and come in various types to suit different needs.
Indexed arrays are useful for simple lists, associative arrays allow for key-value pairs, and
multidimensional arrays are useful for more complex data. Understanding how to work with arrays is
crucial for developing efficient PHP applications.