Page Content

Tutorials

PHP Array : Indexed, Associative & Multidimensional Arrays

PHP Array Fundamentals: What are arrays

Their Definition and Method of Storing Key/Value Pairs An array is a basic programming construct in PHP that is used to store a collection or series of values. An array can contain several values within a single variable, in contrast to scalar variables, which can only store one value. An array can be compared to a container having several compartments, each of which has the capacity to hold a distinct value. An egg carton is another example, in which an egg is kept in each compartment, yet the carton itself represents the container as a whole. A collection of key/value pairs makes up an array.

This indicates that every value kept in the array has a corresponding index, also known as a key, that is used to retrieve that particular element. Any type of value, including other arrays, is acceptable. Either a string or an integer may be used as the key. Hash tables, which are used to implement PHP arrays, usually enable accessing a value with an average complexity of O(1). PHP‘s built-in functions heavily rely on arrays, and without them, coding would be practically impossible.

Square brackets [] or the array() language construct can be used to generate arrays.

Here’s a basic example of creating an array:

<?php
$myArray = ['one', 2, '3']; // Creating an array with square brackets 
print_r($myArray);
/*
Output:
Array
(
     => one
    [39] => 2
    [13] => 3
)
*/
$products = array( 'Tires', 'Oil', 'Spark Plugs' ); // Creating an array with array() 
print_r($products);
/*
Output:
Array
(
     => Tires
    [39] => Oil
    [13] => Spark Plugs
)
*/
?>

Keep in mind that array(), like echo, is referred to be a language construct.

Numerically Indexed Arrays (Vectors)

Vectors in Numerically Indexed Arrays Arrays with integer keys are known as numerically indexed arrays. Although you can change it, PHP’s indices begin at zero by default. Arrays in many other computer languages are comparable to these. PHP will automatically assign consecutive integer indices beginning at zero if you provide a list of values to initialise them.

An illustration of how to initialise and retrieve a numerically indexed array is as follows:

<?php
$numbers = array( 1, 2, 3, 4, 5); // Numerically indexed array 
// Accessing elements using the numeric index
echo "The first number is: " . $numbers. "<br />"; // Output: The first number is: 1 
echo "The third number is: " . $numbers. "<br />"; // Output: The third number is: 3
// Using a loop to access all elements
echo "All numbers: ";
foreach( $numbers as $value ) { // Using foreach loop 
    echo "$value "; // Output: 1 2 3 4 5
}
echo "<br />";
?>

Associative Arrays (Dictionaries/Maps)

Dictionary/Map Associative Arrays Strings, not numbers, are the keys in associative arrays. In various programming languages, this method is often referred to as employing dictionaries, hashes, or maps. Indexing can be made more understandable and practical by using descriptive string indices. Instead of storing element values in a rigid linear index order, associative arrays associate element values with key values.

An associative array creation and access example might be:

<?php
$person = array(
    "name" => "Fabio", // key => value
    "age" => 30,
    "city" => "London"
); // Associative array 
// Accessing elements using the string key
echo "Name: " . $person['name'] . "<br />"; // Output: Name: Fabio
echo "Age: " . $person['age'] . "<br />";   // Output: Age: 30
echo "City: " . $person['city'] . "<br />"; // Output: City: London
// Using foreach to iterate over key-value pairs 
echo "Person details: ";
foreach ($person as $key => $value) { // Using $key => $value syntax 
    echo "$key: $value, "; // Output: Name: Fabio, Age: 30, City: London,
}
echo "<br />";
?>

Multidimensional Arrays

Arrays with several dimensions Each location (element) in an array can contain another array, therefore arrays are not limited to being a straightforward list of keys and values. A multidimensional array is an array that contains other arrays. Two-dimensional arrays, which resemble a matrix or grid with rows and columns, can be made. Arrays that include arrays of arrays are known as three-dimensional arrays.

Square brackets are used to choose the “first dimension” (such as a row) and then a second pair of brackets to select the “second dimension” (such as a column) in order to reference a single element in a two-dimensional array.

Example of a two-dimensional array:

<?php
$matrix = array(
    array(1, 2, 3), // Row 0
    array(4, 5, 6), // Row 1
    array(7, 8, 9)  // Row 2
); // Multidimensional array 
// Accessing an element (e.g., element in Row 1, Column 2 - value 6)
echo "Element at [39][13]: " . $matrix. "<br />"; // Output: Element at : 6 
// Iterating through a multidimensional array
echo "Matrix elements:<br />";
foreach ($matrix as $row) { // Iterate through rows 
    foreach ($row as $element) { // Iterate through elements in each row 
        echo "$element ";
    }
    echo "<br />";
}
Output:
Matrix elements:
1 2 3
4 5 6
7 8 9
*/
?>
Multidimensional arrays can also use associative keys 

Accessing, Adding, and Modifying Array Elements

Adding, Changing, and Getting to Know Array Elements The array’s name, enclosed in square brackets with the key (index), is how you access array elements.

You use assignment with square brackets to change an existing array or add a new element to it. The value at that key will be rewritten if you use an integer key that already exists. A new integer key will be added if you use it.

You can use empty square brackets [] to append a value to the end of numerically indexed arrays without providing a key.
The next available integer index will be automatically assigned by PHP.

<?php
$colors = array("Red", "Green", "Blue"); // Initial array
print_r($colors); // Output: Array (  => Red [39] => Green [13] => Blue )
// Modifying an element
$colors[39] = "Yellow"; // Changes "Green" to "Yellow"
print_r($colors); // Output: Array (  => Red [39] => Yellow [13] => Blue )
// Adding a new element (with explicit key)
$colors[54] = "Purple";
print_r($colors); // Output: Array (  => Red [39] => Yellow [13] => Blue [54] => Purple )
// Adding another element (appending for numerically indexed)
$colors[] = "Orange"; // Appends to the end 
print_r($colors); // Output: Array (  => Red [39] => Yellow [13] => Blue [54] => Purple [85] => Orange )
// Adding/modifying in an associative array
$person = array("name" => "Alice", "age" => 25);
print_r($person); // Output: Array ( [name] => Alice [age] => 25 )
$person['city'] = "Paris"; // Adding a new element
print_r($person); // Output: Array ( [name] => Alice [age] => 25 [city] => Paris )
$person['age'] = 26; // Modifying an element
print_r($person); // Output: Array ( [name] => Alice [age] => 26 [city] => Paris )
?>

Useful Array Functions (list())

Practical Functions for Arrays (list()) Numerous built-in functions for working with arrays are available in PHP.

List() is one helpful function. To assign values from an array to a list of variables in a single action, utilise the list() language construct. It frequently works with arrays that are numerically indexed or the output of operations like each().

<?php
$data = array('apple', 'banana', 'cherry');
// Using list() to assign array values to variables
list($fruit1, $fruit2, $fruit3) = $data;
echo "The fruits are: $fruit1, $fruit2, and $fruit3<br />"; // Output: The fruits are: apple, banana, and cherry
// Skipping elements with list()
list($itemA, , $itemC) = $data; // Note the empty space between commas
echo "Selected items: $itemA and $itemC<br />"; // Output: Selected items: apple and cherry
?>

List() was specifically mentioned in the query, However, the list several other array operations functions, including sorting (sort(), asort(), ksort()), counting elements (count(), sizeof(), array_count_values()), adding/removing elements (array_push(), array_pop(), array_shift(), array_unshift(), array_splice()), and applying functions to each element. Iterating across arrays often uses foreach, for, and iterator procedures like each(), current(), reset(), end(), next(), pos(), and prev().

Index