In PHP, an array is essentially a map that has been arranged. A map is a type that associates values with their corresponding keys.
In programming, an array is a particular variable that may contain several values at the same time. This type is well-suited for a variety of applications; it may be used as an array, list (vector), a hash table, dictionary, collection, stack, queue, and possibly many other things.
Due to the fact that array values may be any other array, trees and multidimensional arrays are also possibilities.
An array can be created by the array() language construct. It takes a certain number of comma-separated key => value pairs.
array( [key =>] value , ... ) // key may be an integer or string // value may be any value <?php $arr = array("foo" => "bar", 12 => true); echo $arr["foo"]; // bar echo $arr; // 1 ?>
A key may be either an integer or a string. If a key is the standard representation of an integer, it will be interpreted as such (i.e., “8” will be interpreted as 8, while “08” will be interpreted as “08”). There are no different indexed and associative array types in PHP; there is only one array type, which can both contain integer and string indices.
A value can be of any PHP type.
<?php $arr = array("somearray" => array(6 => 5, 13 => 9, "a" => 42)); echo $arr["somearray"]; // 5 echo $arr["somearray"]; // 9 echo $arr["somearray"]["a"]; // 42 ?>
If you do not specify a key for a given value, then the maximum of the integer indices is taken, and the new key will be that maximum value + 1. If you specify a key that already has a value assigned to it, that value will be overwritten.
<?php // This array is the same as ... array(5 => 43, 32, 56, "b" => 12); // ...this array array(5 => 43, 6 => 32, 7 => 56, "b" => 12); ?>
Using TRUE as a key will evaluate integer 1 as key. Using FALSE as a key will evaluate integer 0 as key. Using NULL as a key will evaluate the empty string. Using the empty string as the key will create (or overwrite) a key with the empty string and its value; it is not the same as using empty brackets. You cannot use arrays or objects as keys. Doing so will result in a warning: Illegal offset type.
Types of Arrays in PHP
In PHP, there are three types of arrays:
Numeric array: In a numeric array, you simply need to build items; the internet will give an id to each element automatically. It is sometimes referred to as an indexed array. Arrays that are represented by index numbers are known as numerical arrays, and they are used to represent numbers.
Associative Arrays: The keys of an associative array are strings, which makes it the name for the type of array it is.
Multidimensional Array: This is an array of arrays that is made up of other arrays. Each member of the sub-array has the potential to be an array.