Arrays in PHP

Filter Course


Arrays in PHP

Published by: Sujan

Published date: 16 Jun 2021

Arrays in PHP - Photo

Arrays in PHP

Arrays in PHP are complex variables that allow us to store more than one value or a group of values under a single variable name.

Arrays in PHP

Types of Arrays in PHP

There are three types of arrays that you can create. These are:

  • Indexed array — An array with a numeric key.
  • Associative array — An array where each key has its own specific value.
  • Multidimensional array — An array containing one or more arrays within itself.

 

Indexed Arrays

An indexed or numeric array stores each array element with a numeric index.

Arrays in PHP

Associative Arrays

In an associative array, the keys assigned to values can be arbitrary and user-defined strings.

Arrays in PHP

The following example is equivalent to the previous example, but shows a different way of creating associative arrays:

Arrays in PHP

Multidimensional Arrays

The multidimensional array is an array in which each element can also be an array and each element in the sub-array can be an array or further contain an array within itself and so on.

Arrays in PHP

Viewing Array Structure and Values

You can see the structure and values of an array by using one of two statements — var_dump() or print_r(). The print_r() statement, however, gives somewhat less information.

Arrays in PHP

The print_r() statement gives the following output:

Array ( [0] => London [1] => Paris [2] => New York )

This output shows the key and the value for each element in the array.

 

The var_dump() statement gives the following output:

array(3) { [0]=> string(6) "London" [1]=> string(5) "Paris" [2]=> string(8) "New York" }

This output shows the data type of each element, such as a string of 6 characters.