FriconiX
Free collection of beautiful vector icons for your web pages.

Lesson 3.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 ]:

See also


Last update : 01/17/2020