PHP Arrays
PHP arrays are special variables that can hold more than one value at a time. Rather than creating multiple variables to store related data, arrays group data logically under one variable name. PHP supports three main types of arrays:
- Indexed Arrays: Arrays having a numeric index.
- Associative Arrays: Arrays having named keys.
- Multidimensional Arrays: Arrays having one or more arrays in it.
Creating PHP Arrays
There are different ways to create a PHP array. Let’s check them out one-by-one.
Indexed Arrays
The PHP array() construct can be used to create an indexed array:
$colors = array("Red", "Green", "Blue");
Here is a shorter syntax that can also be used to create an indexed array:
$colors = ["Red", "Green", "Blue"];
Associative Arrays
An associative array can be created like this:
$person = ["name" => "John","age" => 30,];
Multidimensional Arrays
A multidimensional array can be created like this:
$users = [["name" => "Alice", "age" => 25],["name" => "Bob", "age" => 28]];
Accessing PHP Arrays
There are different ways to access the elements of a PHP array. Let’s check them out one-by-one.
Indexed Arrays
This example accesses the first item in the indexed array colors:
<?php$colors = ["Red", "Green", "Blue"];echo $colors[0]; // Output: Red?>
Associative Arrays
This example accesses the value associated with the "name" key in the associative array person:
<?php$person = ["name" => "John","age" => 30];echo $person["name"]; // Output: John?>
Multidimensional Arrays
This example accesses the value associated with the "name" key for the second user in the multidimensional array users:
<?php$users = [["name" => "Alice", "age" => 25],["name" => "Bob", "age" => 28]];echo $users[1]["name"]; // Output: Bob?>
Updating PHP Arrays
This example updates the second item of the indexed array colors and the value associated with the key "age" in the associative array person:
<?php$colors = ["Red", "Green", "Blue"];$colors[1] = "Yellow";$person = ["name" => "John","age" => 30];$person["age"] = 31;print_r($colors[1]);print_r("\n");print_r($person["age"]);?>
Here is the output:
Yellow31
Adding Items to a PHP Array
This example adds a new item to the indexed array colors and a new key-value pair to the associative array person:
<?php$colors = ["Red", "Green"];$colors[] = "Purple";$person = ["name" => "John","age" => 30];$person["city"] = "New York";print_r($colors);print_r("\n");print_r($person);?>
Here is the output:
Array([0] => Red[1] => Green[2] => Purple)Array([name] => John[age] => 30[city] => New York)
Removing Items from a PHP Array
This codebyte example uses the unset() function to remove an item from the indexed array colors and a key-value pair from the associative array person:
Frequently Asked Questions
1. How do I check if a value exists in a PHP array?
You can check if a value exists in a PHP array using in_array() and array_key_exists():
<?php$colors = ["Red", "Green", "Blue"];$person = ["name" => "Alice", "age" => 25];if (in_array("Red", $colors)) {echo "Red is in the array.\n";}if (array_key_exists("name", $person)) {echo "The 'name' key exists.\n";}?>
Here is the output:
Red is in the array.The 'name' key exists.
2. How can I loop through a PHP array?
You can use foreach to loop through a PHP array:
<?php$colors = ["Red", "Green", "Blue"];foreach ($colors as $color) {echo $color . "\n";}$person = ["name" => "Alice", "age" => 25];foreach ($person as $key => $value) {echo "$key: $value\n";}?>
Here is the output:
RedGreenBluename: Aliceage: 25
3. How do I count the number of elements in a PHP array?
You can use the built-in count() function to determine how many elements a PHP array contains:
<?php$colors = ["Red", "Green", "Blue"];echo "Total colors: " . count($colors);print_r("\n");$person = ["name" => "John","age" => 30,];echo "Total fields: " . count($person);?>
Here is the output:
Total colors: 3Total fields: 3
Arrays
- array()
- Returns an array that can be either indexed, associative or multidimensional.
- array_chunk()
- Splits an array into a number of specified chunks.
- array_column()
- Returns the values from a single column in the input array.
- array_combine()
- Returns a new array by combining two arrays, where one array represents keys and the other array represents values.
- array_count_values()
- Counts the occurrences of values in an array.
- array_fill()
- Fills an array with values and returns the filled array.
- array_flip()
- Interchanges the keys and values of an array.
- array_intersect()
- Returns the matching values of two or more arrays.
- array_keys()
- Returns all keys or a subset of the keys of a given array.
- array_map()
- Creates a new array by applying a callback function to each element of an existing array.
- array_merge()
- Merges one or more arrays to form a single array.
- array_pad()
- Pads an array to a specified length with a value.
- array_pop()
- Removes the last element of an array.
- array_push()
- Adds one or more element values to the end of an array, and returns the updated array.
- array_rand()
- Used to select one or more random keys from an array.
- array_reduce()
- Iterates through an array to produce a single value.
- array_replace()
- Used to replace the values of an array with values from one or more arrays.
- array_reverse()
- Reverses the items in an array and returns the reversed array.
- array_search()
- Searches an array for a given value and returns the first matching key for that value.
- array_shift()
- Pops an element off the beginning of an array.
- array_splice()
- Removes a set of elements from an array and replaces them with a new set of elements.
- array_unique()
- Returns an array without duplicate values.
- array_values()
- Returns all of the values in a given array.
- compact()
- Returns an array from variables and their values.
- extract()
- Uses an array of keys and values to create variables in the current symbol table.
- range()
- Returns an array that contains a series of elements based on the parameters given.
- rsort()
- Sorts a given array in descending order.
- shuffle()
- Randomizes the indexes of the elements in a given array.
- sort()
- Sorts an array in ascending order.
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn PHP on Codecademy
- Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!
- Includes 6 Courses
- With Professional Certification
- Beginner Friendly.75 hours