PHP Arrays
In this tutorial, we will learn about PHP arrays. When you declare a variable in a PHP program, you can assign only one value to it at a time. This is a limitation of variables in a program.
In certain cases, you may need to store more than one value. What will you do?
You will define multiple variables to store multiple data in the program. But, this method is very time consuming and makes the program lengthy. Therefore, you can use PHP arrays to minimize the size of the program.
Arrays overcome this limitation by allowing you to store and manage multiple values within a single variable. This feature makes arrays a powerful data structure for handling collections of data.
An array is one of the most powerful and versatile data structures in PHP that allows you to store and manage values or data under a single variable name.
In simple words, an array is a data structure that stores multiple values in a single variable. This special variable can store various types of data, including numbers, strings, objects, or even other arrays. It is important to note that PHP implements arrays as ordered maps, where each key is mapped to a corresponding value.
Arrays in PHP are dynamic in nature, meaning that they can grow or shrink as needed during the execution of the program. This flexibility allows you to add or remove elements at any time. Hence, this makes arrays a powerful tool for handling data in various scenarios, such as storing user information, managing database records, or processing form inputs.
How to Create Arrays in PHP?
In PHP, there are several ways to create arrays. The most common ways to create arrays in PHP are as follows:
- Using the array() Function
- Using short array syntax ([ ])
- By using the initialization method
1. Using the array() Function:
You can create a single-dimensional array using the built-in array() function. The general syntax is as follows:
$array_name = array(value1, value2, value3, . . . . .);
Here, $array_name is the name of an array and value1, value2, value3, . . . are the array elements or items. The array elements can be of any type of data. You can have different data types in the same array. The most common are numbers (int, float) and strings. However, the array elements can also be objects, functions or even arrays.
Example 1:
$num = array(2, 4, 6, 8, 10); // An array with five elements.
In this example, we have created an array of five elements using a built-in PHP array() function. The array() function takes a comma-separated list of values and stores them as elements of the array.
The $num is a reference variable that holds the array object. In PHP, an array variable does not directly store an array itself. It is basically a reference variable that points to an array object stored in the memory.
PHP automatically assigns an index value starting from 0 for each value in an indexed array. For example:
$num[0] = 2;
$num[1] = 4;
$num[2] = 6;
$num[3] = 8;
$num[4] = 10;
The number used to uniquely identify each element of an array is called the array index. This index allows you to access or modify elements individually.
Example 2:
$fruits = array("Apple", "Banana", "Cherry", "Orange"); // An array with four elements.
Example 3:
$myArr = array("John", 20, ["Apples", "Oranges"], myFunction); // An array with four different data types.
2. Using Square Brackets ([])
This is the modern and more concise way to create arrays. It is introduced in PHP 5.4 version. The general syntax is as follows:
$array_name = [value1, value2, value3, value4, . . . . . ];
Example 4:
$languages = ["Java", "Python", "PHP"];
Line breaks are not important, so you can also create an array in multiple lines like this:
$languages = [
"Java",
"Python",
"PHP"
];
3. Initialization Method
This is another way of initializing an array in PHP in which you can initialize an array by assigning values to specific indices or keys one at a time. This method is useful when:
- You don’t know all the values or data at the time of array creation.
- You want to add elements dynamically based on conditions.
Let’s take an example in which an array $FriendNames will store five friend’s names by using initialization method.
Example 5:
// Array with initialization method.
$FriendNames[0] = "John";
$FriendNames[1] = "Bob";
$FriendNames[2] = "Saanvi";
$FriendNames[3] = "Tripti";
$FriendNames[4] = "Mark";
In this example, we have created an array of five elements by assigning string values to array indexes. So, its size is five. $FriendName is the name of the array. It is one-dimensional or linear array.
Accessing Array Elements in PHP
There are several ways to display data from an array. The most common ways to access and display array elements are as follows:
- Using array index
- for loop
- print_r() function
- foreach loop
Let’s understand each one by one.
1. Using Array Index
You can access elements of an array by using its array index. This method works for both indexed and associative arrays.
Example 6:
<?php
// Creating an array of four elements of type string.
$FriendNames = ["John", "Bob", "Saanvi", "Mark"];
// Accessing elements of the array.
echo $FriendNames[0] . "\n";
echo $FriendNames[1] . "\n";
echo $FriendNames[2] . "\n";
echo $FriendNames[3];
?>
Output: John Bob Saanvi Mark
2. Using for loop
You can iterate over an array using for loop. It is suitable for indexed arrays where indices are sequential integers. Let’s take an example on it.
Example 7:
<?php
// Creating an array of four elements of type integer.
$numbers = [10, 20, 30, 40];
// Call count() function to count elements of the array.
$len = count($numbers);
// Applying for loop.
for ($i = 0; $i < $len; $i++) {
echo $numbers[$i] . " ";
}
?>
Output: 10 20 30 40
3. Using print_r() Function
This function returns the entire structure of an array in a human readable form, including keys and values. It is the best used for debugging purpose.
Example 8:
<?php
$fruits = ["Apple", "Banana", "Cherry", "Orange"];
print_r($fruits);
?>
Output: Array ( [0] => Apple [1] => Banana [2] => Cherry [3] => Orange )
4. Using foreach Loop
This is the most simple method to iterate over elements in an array. You can apply this method on both indexed and associative arrays. This method automatically handles keys and values.
Example 9:
<?php
$fruits = ["Apple", "Banana", "Cherry", "Orange"];
foreach ($fruits as $fruit) {
echo $fruit . " ";
}
?>
Output: Apple Banana Cherry Orange
Key Features of Arrays in PHP
There are several key features of arrays in PHP. They are as follows:
- PHP arrays are ordered collections of elements, where each element is stored in a specific order. You can access it by using keys.
- Arrays in PHP can store values of mixed data types, such as integers, strings, objects, and even other arrays. They do not need to be of the same type.
- An array can grow or shrink dynamically. There’s no need to declare its size in advance when you create it.
- PHP arrays can either be indexed or associative. Indexed arrays use numeric indices starting from 0 by default, while associative arrays use custom string keys for each element.
- PHP implements arrays as ordered maps, where each key is mapped to a corresponding value.
- PHP internally uses the hash table data structure to store and manage arrays.
- Arrays are dynamic in nature in PHP, meaning that you can add, remove, or modify elements at runtime with no need to reallocate the entire array.
How PHP Stores Array Elements in Memory?
When you create an array, PHP internally allocates memory for it. Each element of an array is stored as a key-value pair in the underlying data structure. Each key is mapped to a corresponding value.
PHP internally uses a hash table data structure to store the keys and values of an array and maintains the order of insertion. For an indexed array, PHP automatically uses numeric keys by default if no key is specified.
// Indexed Array
$fruits = ["Apple", "Banana", "Cherry", "Orange"];
// Internal Representation in PHP's Hash Table:
Key 0 -> Value "Apple"
Key 1 -> Value "Banana"
Key 2 -> Value "Cherry"
Key 3 -> Value "Orange"
For associative arrays, PHP hashes string keys and maps them to their corresponding values.
$fruits = ["A" => "Apple", "B" => "Banana", "C" => "Cherry", "D" => "Orange"];
// Internal representation:
Hash("A") -> "Apple"
Hash("B") -> "Banana"
Hash("C") -> "Cherry"
Hash("D") -> "Orange"
Note that PHP hashes string keys using a hashing algorithm to generate a unique hash value. This hash value determines the location of the corresponding key-value pair in the hash table.
However, PHP does not hash numeric keys. They are used directly to locate their corresponding values in the hash table. This distinction allows PHP arrays to handle both associative and indexed arrays efficiently.
Mixed Keys
PHP arrays can also handle a mix of string and numeric keys. In such cases, string keys are hashed, while numeric keys are directly used without hashing. For example:
$array = [1 => "Apple", "fruit" => "Banana"];
// Internally representation:
Key 1 -> "Apple"
Hash("fruit") -> "Banana"
PHP dynamically allocates memory for arrays. When you add a new element in the array, PHP dynamically resizes the hash table to accommodate them if necessary.
Types of Arrays in PHP
There are mainly three types of arrays in PHP programming language. They are as:
- Indexed array
- Associative array
- Multidimensional array
You will understand indexed, associative, and multidimensional arrays in PHP one by one in the next tutorial.