An array is a special variable, which can hold more than one value at a time.
An array stores multiple values in one single variable:
$cars = array("Volvo", "BMW", "Toyota");
In PHP, there are three types of arrays:
In PHP, there are several pre-defined arrays functions, which can be used to work with arrays.
Array items can be of any data type.
The most common are strings and numbers (int, float), but array items can also be objects, functions or even
arrays.
You can have different data types in the same array.
Array items of four different data types:
$myArr = array("Volvo", 15, ["apples", "bananas"], myFunction);
The real strength of PHP arrays are the built-in array functions, like the count()
function for
counting array items:
$cars = array("Volvo", "BMW", "Toyota");
echo count($cars);
An indexed array is an array that uses numerical keys.
The keys are assigned automatically.
Create and display an indexed array:
$cars = array("Volvo", "BMW", "Toyota");
var_dump($cars);
You access an array element by referring to its index number inside square brackets [].
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[0];
You access an array element by referring to its index number inside square brackets [].
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[0];
To change the value of a specific indexed array, refer to the index number, and use the assignment operator (=)
Change the value of the second item:
$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
var_dump($cars);
To loop through and print all the values of an indexed array, you could use a foreach
loop, like
this:
Display all array items:
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as $x) {
echo "$x <br>";
}
In PHP, index numbers typically refer to the position of an element within an array.
Each element in an array has an index number that indicates its position, starting from 0 for the first element.
New items get the next index number, meaning one higher than the highest existing index.
So if you have an array like this:
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
And if you use the array_push()
function to add a new item, the new item will get the index 3:
array_push($cars, "Ford");
var_dump($cars);
But if you have an array with random index numbers, like this:
$cars[5] = "Volvo";
$cars[7] = "BMW";
$cars[14] = "Toyota";
And if you use the array_push()
function to add a new item, what will be the index number of the
new item?
array_push($cars, "Ford");
var_dump($cars);
Associative arrays are arrays that use named keys that you assign to them.
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
var_dump($car);
To access an array item you can refer to the key name.
Display the model of the car:
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
echo $car["model"];
To change the value of an array item, use the key name:
Change the year
item:
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
$car["year"] = 2024;
var_dump($car);
You can loop through each key/value pair in an associative array with the foreach
loop
Display all array items, keys and values:
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
foreach ($car as $x => $y) {
echo "$x: $y <br>";
}
You can create arrays by using the array()
function:
Create an array:
$cars = array("Volvo", "BMW", "Toyota");
You can also use a shorter syntax by using the []
brackets:
$cars = ["Volvo", "BMW", "Toyota"];
You can also create an array with multiple lines:
$cars = [
"Volvo",
"BMW",
"Toyota"
];
PHP 5 allows you to end an array declaration with a trailing comma:
$cars = [
"Volvo",
"BMW",
"Toyota",
];
When creating indexed arrays the keys are given automatically, starting at 0 and increased by 1 for each item, so the array above could also be created with keys:
$cars = [
0 => "Volvo",
1 => "BMW",
2 =>"Toyota"
];
As you can see, indexed arrays are the same as associative arrays, but associative arrays have names instead of numbers:
$myCar = [
"brand" => "Ford",
"model" => "Mustang",
"year" => 1964
];
You can declare an empty array first, and add items to it later:
$cars = [];
$cars[0] = "Volvo";
$cars[1] = "BMW";
$cars[2] = "Toyota";
The same goes for associative arrays, you can declare the array first, and then add items to it:
$myCar = [];
$myCar["brand"] = "Ford";
$myCar["model"] = "Mustang";
$myCar["year"] = 1964;
You can have arrays with both indexed and named keys:
$myArr = [];
$myArr[0] = "apples";
$myArr[1] = "bananas";
$myArr["fruit"] = "cherries";
To access an array item, you can refer to the index number for indexed arrays, and the key name for associative arrays.
Access an item by referring to its index number:
$cars = array("Volvo", "BMW", "Toyota");
echo $cars[2];
Note: The first item has index 0.
To access items from an associative array, use the key name:
Access an item by referring to its key name:
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
echo $cars["year"];
In PHP, the keys of an associative array are always strings. If you don't use double quotes, the key will be quoted as a string
You can use both double and single quotes when accessing an array:
echo $cars["model"];
echo $cars['model'];
Array items can be of any data type, including function.
To execute such a function, use the index number followed by parentheses ()
:
Execute a function item:
function myFunction() {
echo "I come from a function!";
}
$myArr = array("Volvo", 15, myFunction);
$myArr[2]();
Use the key name when the function is an item in a associative array:
Execute function by referring to the key name:
function myFunction() {
echo "I come from a function!";
}
$myArr = array("car" => "Volvo", "age" => 15, "message" => myFunction);
$myArr["message"]();
To loop through and print all the values of an associative array, you can use a foreach
loop, like this:
Display all array items, keys and values:
$car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
foreach ($car as $x => $y) {
echo "$x: $y <br>";
}
To loop through and print all the values of an indexed array, you can use a foreach
loop, like this:
Display all array items:
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as $x) {
echo "$x <br>";
}
You can also change the value of an indexed array element by using the array
key
and its
new value
:
Change the second array item from "BMW" to "Ford":
$cars = array("Volvo", "BMW", "Toyota");
$cars[1] = "Ford";
Note: The first item has index 0.
There are different techniques to use when changing item values in a foreach loop.
One way is to insert the & character in the assignment to assign the item value by reference, and thereby making sure that any changes done with the array item inside the loop will be done to the original array:
Change ALL item values to "Ford":
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as &$x) {
$x = "Ford";
}
unset($x);
var_dump($cars);
Note: Remember to add the unset()
function after the loop.
Without the unset($x)
function, the$x
variable will remain as a reference to the last array item.
To demonstrate this, see what happens when we change the value of $x
after the foreach loop:
Demonstrate the consequence of forgetting the
$cars = array("Volvo", "BMW", "Toyota");
foreach ($cars as &$x) {
$x = "Ford";
}
$x = "ice cream";
var_dump($cars);
To add items to an existing array, you can use the bracket []
syntax.
Add one more item to the fruits array:
$fruits = array("Apple", "Banana", "Cherry");
$fruits[] = "Orange";
To add items to an associative array, or key/value array, use brackets []
for the key, and assign value with the =
operator.
Add one item to the car
array:
$cars = array("brand" => "Ford", "model" => "Mustang");
$cars["color"] = "Red";
To add multiple items to an existing array, use the array_push()
function.
Add three item to the fruits
array:
$fruits = array("Apple", "Banana", "Cherry");
array_push($fruits, "Orange", "Kiwi", "Lemon");
To add multiple items to an existing array, you can use the +=
operator.
Add two items to the cars
array:
$cars = array("brand" => "Ford", "model" => "Mustang");
$cars += ["color" => "red", "year" => 1964];
To remove an existing item from an array, you can use the array_splice()
function.
With the array_splice()
function you specify the index (where to start) and how many items you want to delete.
Remove the second item:
$cars = array("Volvo", "BMW", "Toyota");
array_splice($cars, 1, 1);
After the deletion, the array gets reindexed automtically, starting at index 0.
You can also use the unset()
function to delete existing array items.
Note: The unset()
function does not re-arrange the indexes, meaning that after deletion the array will no longer contain the missing indexes.
Remove the second item:
$cars = array("Volvo", "BMW", "Toyota");
unset($cars[1]);
You can remove multiple array items by using the array_splice()
function.
Remove 2 items, starting a the second item (index 1):
$cars = array("Volvo", "BMW", "Toyota");
array_splice($cars, 1, 2);
The unset()
function takes a unlimited number of arguments, and can therefor be used to delete multiple array items:
$cars = array("Volvo", "BMW", "Toyota");
unset($cars[0], $cars[1]);
To remove items from an associative array, you can use the unset()
function.
Specify the key of the item you want to delete.
Remove the "model":
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
unset($cars["model"]);
You can also use the array_diff()
function to remove items from an associative array.
This function returns a new array, without the specified items.
Create a new array, without "Mustang" and "1964":
$cars = array("brand" => "Ford", "model" => "Mustang", "year" => 1964);
$newarray = array_diff($cars, ["Mustang", 1964]);
Note: The array_diff() function takes values as parameters, and not keys.
The array_pop()
function removes the last item of an array.
Remove the last item:
$cars = array("Volvo", "BMW", "Toyota");
array_pop($cars);
The array_shift()
function removes the first item of an array.
$cars = array("Volvo", "BMW", "Toyota");
array_shift($cars);
PHP has a set of built-in functions that you can use on arrays.
Function | Description |
---|---|
array() | Creates an array |
array_change_key_case() | Changes all keys in an array to lowercase or uppercase |
array_chunk() | Splits an array into chunks of arrays |
array_column() | Returns the values from a single column in the input array |
array_combine() | Creates an array by using the elements from one "keys" array and one "values" array |
array_count_values() | Counts all the values of an array |
array_diff() | Compare arrays, and returns the differences (compare values only) |
array_diff_assoc() | Compare arrays, and returns the differences (compare keys and values) |
array_diff_key() | Compare arrays, and returns the differences (compare keys only) |
array_diff_uassoc() | Compare arrays, and returns the differences (compare keys and values, using a user-defined key comparison function) |
array_diff_ukey() | Compare arrays, and returns the differences (compare keys only, using a user-defined key comparison function) |
array_fill() | Fills an array with values |
array_fill_keys() | Fills an array with values, specifying keys |
array_filter() | Filters the values of an array using a callback function |
array_flip() | Flips/Exchanges all keys with their associated values in an array |
array_intersect() | Compare arrays, and returns the matches (compare values only) |
array_intersect_assoc() | Compare arrays and returns the matches (compare keys and values) |
array_intersect_key() | Compare arrays, and returns the matches (compare keys only) |
array_intersect_uassoc() | Compare arrays, and returns the matches (compare keys and values, using a user-defined key comparison function) |
array_intersect_ukey() | Compare arrays, and returns the matches (compare keys only, using a user-defined key comparison function) |
array_key_exists() | Checks if the specified key exists in the array |
array_keys() | Returns all the keys of an array |
array_map() | Sends each value of an array to a user-made function, which returns new values |
array_merge() | Merges one or more arrays into one array |
array_merge_recursive() | Merges one or more arrays into one array recursively |
array_multisort() | Sorts multiple or multi-dimensional arrays |
array_pad() | Inserts a specified number of items, with a specified value, to an array |
array_pop() | Deletes the last element of an array |
array_product() | Calculates the product of the values in an array |
array_push() | Inserts one or more elements to the end of an array |
array_rand() | Returns one or more random keys from an array |
array_reduce() | Returns an array as a string, using a user-defined function |
array_replace() | Replaces the values of the first array with the values from following arrays |
array_replace_recursive() | Replaces the values of the first array with the values from following arrays recursively |
array_reverse() | Returns an array in the reverse order |
array_search() | Searches an array for a given value and returns the key |
array_shift() | Removes the first element from an array, and returns the value of the removed element |
array_slice() | Returns selected parts of an array |
array_splice() | Removes and replaces specified elements of an array |
array_sum() | Returns the sum of the values in an array |
array_udiff() | Compare arrays, and returns the differences (compare values only, using a user-defined key comparison function) |
array_udiff_assoc() | Compare arrays, and returns the differences (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values) |
array_udiff_uassoc() | Compare arrays, and returns the differences (compare keys and values, using two user-defined key comparison functions) |
array_uintersect() | Compare arrays, and returns the matches (compare values only, using a user-defined key comparison function) |
array_uintersect_assoc() | Compare arrays, and returns the matches (compare keys and values, using a built-in function to compare the keys and a user-defined function to compare the values) |
array_uintersect_uassoc() | Compare arrays, and returns the matches (compare keys and values, using two user-defined key comparison functions) |
array_unique() | Removes duplicate values from an array |
array_unshift() | Adds one or more elements to the beginning of an array |
array_values() | Returns all the values of an array |
array_walk() | Applies a user function to every member of an array |
array_walk_recursive() | Applies a user function recursively to every member of an array |
arsort() | Sorts an associative array in descending order, according to the value |
asort() | Sorts an associative array in ascending order, according to the value |
compact() | Create array containing variables and their values |
count() | Returns the number of elements in an array |
current() | Returns the current element in an array |
each() | Deprecated from PHP 7.2. Returns the current key and value pair from an array |
end() | Sets the internal pointer of an array to its last element |
extract() | Imports variables into the current symbol table from an array |
in_array() | Checks if a specified value exists in an array |
key() | Fetches a key from an array |
krsort() | Sorts an associative array in descending order, according to the key |
ksort() | Sorts an associative array in ascending order, according to the key |
list() | Assigns variables as if they were an array |
natcasesort() | Sorts an array using a case insensitive "natural order" algorithm |
natsort() | Sorts an array using a "natural order" algorithm |
next() | Advance the internal array pointer of an array |
pos() | Alias of current() |
prev() | Rewinds the internal array pointer |
range() | Creates an array containing a range of elements |
reset() | Sets the internal pointer of an array to its first element |
rsort() | Sorts an indexed array in descending order |
shuffle() | Shuffles an array |
sort() | Sorts an indexed array in ascending order |
uasort() | Sorts an array by values using a user-defined comparison function and maintains the index association |
uksort() | Sorts an array by keys using a user-defined comparison function |
usort() | Sorts an array by values using a user-defined comparison function |