PHP Arrays

Arrays are advanced variables that let us store multiple values or groups of values under one variable name. Consider the following scenario: you want to save colors in your PHP script. Putting the colors in a variable one by one might look like this:


<?php
  $color1 = "Red";
  $color2 = "Green";
  $color3 = "Blue";
?>


But what if you want to store the names of a country's states or cities in variables, and there are hundreds of them? Keeping each city name in its own variable is difficult, tedious, and a bad idea. Array is used in this case.


In PHP, there are several different types of arrays.

You can make three different types of arrays. There are the following:

  • An indexed array, this is an array that is with a numeric key.
  • An associative array is one in which each key has its own unique value.
  • An associative array is one in which each key has its own unique value.


Indexed Array

Each array element in an indexed or numeric array is given a numerical index. The following examples demonstrate two methods for constructing an indexed list, the first of which is the most straightforward:


<?php
  // ndexed array
  $colors = array("Red", "Green", "Blue");
?>



This is analogous to the following example, in which indexes are manually assigned:


<?php
  $colors[0] = "Red";
  $colors[1] = "Green";
  $colors[2] = "Blue";
?>



Associative Array

The keys assigned to values in an associative array may be arbitrary and user defined strings. Instead of index numbers, the list in the following example uses keys:


<?php>
  // associative array
  $ages = array("Peter"=>22, "Clark"=>32, "John"=>28);
?>



The following example is similar to the previous one, but it demonstrates how to make associative arrays in a different way:


<?php
  $ages["Peter"] = "22";
  $ages["Clark"] = "32";
  $ages["John"] = "28";
?>



Multidimensional Array

A multidimensional array is one in which each element can also be an array, and each element in the sub-array can also be an array or contain arrays inside arrays, and so on.

A multidimensional array might look like this:


<?php
  // multidimensional array
  $contacts = array(
  array(
  "name" => "Peter Parker",
  "email" => "peterparker@mail.com",
  ),
  array(
  "name" => "Clark Kent",
  "email" => "clarkkent@mail.com",
  ),
  array(
  "name" => "Harry Potter",
  "email" => "harrypotter@mail.com",
  )
  );
  // Access nested value
  echo "Peter Parker's Email-id is: " . $contacts[0]["email"];
?>