The PHP function array ()
is used to declare arrays. These last are
actually associative array,
i.e. a type that associates values to keys. For example, the table below contains
three values (one, two and three) which are each associated with a key (1, 2 and 3):
$myArray = array (
1 => 'one',
2 => 'two',
3 => 'three'
)
When writing $tableau[2]
you can access to the value associated
to the key 2
, i.e. the string 'two'
.
PHP variables not having a type declaration, it is possible to mix all types of values and keys within a table:
array (
1 => 'one',
'two' => 2,
tab => array (
'key1' => 'Hello',
'key2' => 'world'
),
-5 => TRUE
)
Here is an example of a table containing a list of French criminology students:
$students = array (
0 => array ( 'lastname' => 'Dupont De Ligones', 'firstname' => 'Xavier'),
1 => array ( 'lastname' => 'Louis', 'firstname' => 'Émile'),
2 => array ( 'lastname' => 'Fourniret', 'firstname' => 'Michel'),
3 => array ( 'lastname' => 'Heaulme', 'firstname' => 'Francis')
);
As you can see on the following example, access to the array items is done by
wrting the name of the table followed by key(s) in brackets $arrayName [ key ]
:
PHP arrays comes with a collection of (usefull functions)[https://www.php.net/manual/en/ref.array.php], the most usefull are reported below:
is_array
— Finds whether a variable is an arrayarray_unshift
— Prepend one or more elements to the beginning of an arrayarray_shift
— Shift an element off the beginning of arrayarray_push
— Push one or more elements onto the end of arrayexplode
— Split a string into an arrayimplode
— Join array elements with a stringsort
— Sort an arrayrsort
— Sort an array in reverse orderLet's considere the following array:
$array = array ( 152 , 20, 30, 40, 60 );