Array stores multiple values in one variable:
Using the array() function for creating array
2nd method to create array Using square bracket shorthand [] (available since PHP 5.4):
Creating an Array:
1. Using the array() function.
$fruits = array("apple", "orange", "banana");
2. Using square bracket shorthand (available since PHP 5.4):
$fruits = ["apple", "orange", "banana"];
Array Types:
- Indexed Arrays
- Associative Arrays
- Multidimensional arrays
1. Indexed Arrays:
An indexed array uses numeric index to access elements. The index starts from 0.
<?php
$fruits = array("apple", "orange", "banana");
echo $fruits[1]; // Outputs: orange
?>
2. Associative Arrays:
Associative array use named key to access elements.
<?php
$person = array("name" => "John", "age" => 25, "city" => "New York");
echo $person["name"]; // Outputs: John
?>
3. Multidimensional Arrays:
Array can contain other arrays, Known as multidimensional array.
<?php
$matrix = array(
array(1, 2, 3),
array(4, 5, 6),
array(7, 8, 9)
);
echo $matrix[1][2]; // Outputs: 6
?>
Array Functions:
Array function Name | Definition | Example | |
Basic Functions: | count() | count(): Counts the number of elements in an array. |
|
sizeof() | sizeof(): Alias of count(). |
| |
Adding/Removing Elements: | array_push() | Adds one or more elements to the end of an array. |
|
array_pop() | Removes and returns the last element of an array |
| |
array_unshift() | Adds one or more elements to the beginning of an array |
| |
array_shift() | Removes and returns the first element of an array. |
| |
Merging Arrays: | array_merge() | Merges two or more arrays. |
|
array_merge_recursive() | Recursively merges two or more arrays |
| |
Sorting | sort() | Sorts an array in ascending order. |
|
rsort() | Sorts an array in descending order |
| |
asort() | Sorts an associative array in ascending order, maintaining key-value pairs. |
| |
ksort() | Sorts an associative array by keys in ascending order |
| |
Searching | in_array() | Checks if a value exists in an array. |
|
array_search() | Searches an array for a value and returns the corresponding key if successful. |
| |
array_key_exists() | Checks if a key exists in an array |
| |
Filtering | array_filter() | ilters elements of an array using a callback function. |
|
Others | array_reverse() | Returns an array with elements in reverse order. |
|
array_unique() | Removes duplicate values from an array. |
| |
array_slice() | Returns a slice of an array |
|