Lesson 4.8. PHP arrays

Syntax

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
)

Example

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 ]:

Functions

PHP arrays comes with a collection of (usefull functions)[https://www.php.net/manual/en/ref.array.php], the most usefull are reported below:

Exercice

Let's considere the following array:

$array = array ( 152 , 20, 30, 40, 60 );
  1. Remove the first element of the array
  2. Add 10 at the beginning of the array
  3. Add 70 and 80 at the end of the array
  4. Sort the array in reverse order
  5. Display the final array

See also


Last update : 09/17/2022