PHP 5 Arrays

An array is used to store multiple values, generally of same type, in a single variable.

For example if you have a list of festivals that you want to store together, or may be a list of stationary items, or list of colors, then you can either keep them in separate variables, but then you will have to create a lot of variables and they won't be related to each other.

In such case, PHP arrays are used. Arrays can store multiple values together in a single variable and we can traverse all the values stored in the array using the foreach loop.


Creating an Array

We can create an array in PHP using the array() function.

Syntax:

<?php
/* 
    this function takes multiple values
    separated by comma as input to create
    an aray
*/
array();

?>

In PHP there are 3 types of array:

  1. Indexed Array: These are arrays with numeric index.
  2. Associative Array: These are arrays which have a named key as index, the key can be numeric or text.
  3. Multidimensional Array: These are arrays which contain one or more arrays.

Time for an Example

Let's take a simple example for an array to help you understand how an array is created.

<?php
/* 
    a simple array with car names
*/
$lamborghinis = array("Urus", "Huracan", "Aventador");

?>

To access the data stored in an array, we can either use the index numbers or we can use a foreach loop to traverse the array elements.

Index number for array elements starts from 0, i.e the first element is at the position 0, the second element at position 1 and so on...

<?php
/* 
    a simple array with Lamborghini car names
*/
$lamborghinis = array("Urus", "Huracan", "Aventador");
// print the first car name
echo $lamborghinis[0];
echo "Urus is the latest Super SUV by Lamborghini";

?>

Urus Urus is the latest Super SUV by Lamborghini


Advantages of Array

Here are a few advantages of using array in our program/script:

  1. It's very easy to define simple list of related data, rather than creating multiple variables.
  2. It's super easy to use and traverse using the foreach loop.
  3. PHP provides built-in functions for sorting array, hence it can be used for sorting information as well.