An array is a data structure or a special variable which stores multiple elements which are of the same type and size. An array can consist of elements which are integers, characters or data belonging to any of the other datatypes.
An array is useful in programming because oftentimes we need to store similar values or a list of items as part of a single variable.
Example:
Instead of defining 50 individual variables to store 50 phone numbers we can define an array "$phone_numbers" of length 50 which can be used to store the 50 numbers. Every element of the array is a distinct item that can be accessed using the variable name $phone_numbers and its index position in the array.
Need for Arrays
Simple variables can be used to store simple data .
Example:
A list of variables which store different colors can be defined as shown in the example below. A separate variable is created for each color. It is easy to store this data as only 3 variables need to be defined to store the three colors.
However, when we need to store a large volume of data such as city names or states of a country in variables it can be quite time-consuming and hard to create a huge number of variables each of which need to be created and processed separately. It is very inefficient to create a separate variable for every city and the process can be long and error-prone because of the sheer volume of data that needs to be handled. These disadvantages can be alleviated by using arrays. Arrays offer a convenient way to handle data of a similar type.
The array() function
An array variable is created by using the array() function. The general syntax of declaring and initializing an array variable is
We define an array name using the $ sign just like normal variables. The keyword "array" is used so that the parser knows that the variable being defined is an array variable. The values that the array holds are defined within parenthesis. Each of the values is enclosed by double quotes and all the values are separated by commas.
Example:
Different types of Arrays
PHP supports three different types of arrays. This classification is based on the technique used to access the array elements.
The three different types of arrays are
- Numeric array or Indexed array
- Associative array - Associative arrays are arrays which have a string index, instead of linear storage, each array value can be assigned a specific key.
- Multidimensional array
1. Numeric array or Indexed array
An array with a numeric index is known as a numeric array or an indexed array. Array values are stored and accessed in a linear manner using the array name and the index of the array element.
The index of a numeric array always starts at 0 i.e. the first element in an array always has an index of 0.
Example :
The following is an example of code which creates an indexed array named $countries having three elements. It then prints the list of the three elements in the array.
2. Associative arrays
Associative arrays are arrays which have a string index instead of a regular numeric index. Each array element is a key, value pair where the key which is a user-defined string performs the role of the numeric index i.e the key string is used to access the array elements
For example, if we wish to store the earnings of employees in an array, a numeric array will not be the best choice as it would be difficult to track the employees using system generated number indexes. Instead, we can define an associative array where every element is a pair(key, value) which comprises of the name of the employee and his/her earning. The employee name functions as the key and can be used to access the earnings of specific employees.
Example:
Output:
Payment of Anna is 4000
Payment of Maria is 2000
Payment of Jennifer is 1000
Payment of Anna is 4000
Payment of Maria is 5000
Payment of Jennifer is 1000
3. Multi-dimensional arrays
Multi-dimensional arrays are arrays which contain one or more arrays as elements instead of ordinary elements. There could be nested or multi-dimensional arrays within a multi-dimensional array. Hence multi-dimensional arrays can be 1 or more levels deep.
Multiple dimensions are used to access elements within nested multi-dimensional arrays. However, it is extremely difficult to manage nested arrays that are more than 3 levels deep.
Example:
In the example below, a two-dimensional array is created to store the marks of three students in three subjects .
Code:
Example:
This will produce the following result.
Marks for david in physics : 45
Marks for kevin in maths : 38
Marks for julie in chemistry : 35
Common PHP Array Functions
PHP provides several inbuilt functions to perform some common operations on arrays such as sorting , counting and so on. These functions are convenient because programmers need not write several lines of custom code to perform mundane array operations. Some of the commonly used PHP Array functions are explained in detail below. </p
Count function
The count function is used to count the values that an array contains. If you need to find the number of values in an array you can use Count function as below.
is_array function
The is_array function is used to find out if a variable is an array or not. It returns 1 if the variable is an array and 0 if the variable is not an array.
Sort function
This function sorts the elements in an array according to their values. The rules which are observed while sorting an array are as follows :
- If the array values are alphanumeric, it sorts them in alphabetical order.
- If the array values are numeric, it sorts them in ascending order.
- It removes the existing indices and add new numeric indices.
Example:
<?php $number_array = array(89, 62, 22, 212, 11); sort($number_array); $array_length = count($number_array); for($x = 0; $x < $array_length; $x++) { echo $number_array[$x]; echo "<br />"; } ?>
Output :
11
22
62
89
212
ksort function
This function is used to sort associative arrays by sorting based on the key of each of the elements. The following example illustrates its usage.
Example :
Output:
Array ( [John] => Male [Mary] => Female [Mirriam] => Female )
asort function
The assort function is used to sort an associative array based on the value of each of the elements . It is different from the ksort function because the sorting is done based on the value of each element and not the key.
Example :
Output :
Array ( [John] => 12 [Mary] => 36 [Mirriam] => 45 )
print_r function
The print_r function is used to display the elements of an array in a human readable format.
The syntax of the print_r function is
print_r($array_name)
By passing an extra argument TRUE to the print_r function we can save its output to a variable. If no second argument is mentioned print_r will just display the elements of the array on the screen.
Example:
var_dump function
The var_dump function is so called because it dumps or prints all the information about an array including the number of elements in an array, the types and their values. It is different from the print_r function because in addition to printing the list of array elements in a human-readable format it also:
- Prints the sizes of the variables
- Doesn't print out the non-public data in objects
- It has no return type hence a second parameter cannot be passed to the function specifying that the return value has to be assigned to a variable.
The var_dump function is preferred to the print_r function because it is very useful for debugging purposes because of the comprehensive data that it outputs.
Example :
Using var_dump() function in the previous example rather than print_r() function would give the following output.
Output :
array(3) {
[0]=>
string(6) “Oranges”
[1]=>
string(7) “Apples”
[2]=>
string(5) “Pears”
}
In addition to displaying the total number of elements in the array (3) it also prints each of the elements along with their length.
var_export function:
The var_export() function is used to return structured information about the array variable . Hence the var_export() function is similar to both the var_dump() and print_r() functions. The key difference between the var_export() function and the var_dump function, is that it prints variable information in a format which can be used as PHP code.
Example :
Output :
The extra comma that is seen after the last element will be ignored by PHP and the output can be directly inserted into scripts as shown below.
array_shift function:
The 'array_shift' function deletes the first element of an array and returns the element that has been removed. If the array is an empty array then it returns NULL.
We can choose to store the returned element in a receiving variable or we can choose to display it or perform some other operations on it.
If array_shift is used on an array having numeric keys, after the deletion of the first element the indexes of the remaining elements are modified so that the index of the new array again starts from 0.
Syntax:
array_shift($array)
Example :
We can remove "Apples" from the array $marray shown in the code below and then store it in a variable $fruit.
This function can be quite handy and useful especially when we have a multi-dimensional array posted from a form and the subarray needs to be fetched from the main array.