Arrays in PHP || Server Side Scripting || BCIS Notes

Arrays in PHP || Server Side Scripting || BCIS Notes

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.

Indexed Array

Associative Arrays

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

Associative Array

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

Associative Array

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.

Multidimensional Array

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.

print_r()

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.

 

If you liked our content Arrays in PHP, then you may also like Types of Loops in PHP

Be the first to comment

Leave a Reply

Your email address will not be published.


*