PHP Arrays

PHP Arrays can store multiple values in one single variable.

I. Create Array in PHP

In PHP, the array() function is used to create an array:

array();

There are three types of arrays:

  • Indexed arrays: Arrays with a numeric index
  • Associative arrays: Arrays with named keys
  • Multidimensional arrays: Arrays containing one or more arrays

The elements of an array can be many things other than a string or integer. You can even have objects or other arrays.

1. PHP Indexed Arrays

There are two ways to create indexed arrays:

  • Assign index automatically (index always starts at 0):
$colors = array("Red", "Blue", "Green");
  • Assign index manually:
$colors[0] = "Red";
$colors[1] = "Blue";
$colors[2] = "Green";

Looping through an Indexed Array

We can use For loop to loop through an indexed array:

<?php
$colors = array("Red", "Blue", "Green");
$arrlength = count($colors);

for($x = 0; $x < $arrlength; $x++) {
  echo $colors[$x];
  echo "<br>";
}
?>

2. Associative Arrays

Associative array can be key => value or simply indexed by numbers.

There are two ways to create an associative array:

$age = array("Anna"=>"19", "John"=>"18", "Peter"=>"20");

or:

$age["Anna"] = "19";
$age["John"] = "18";
$age["Peter"] = "20";

Looping Through an Associative Array

To loop through and print all the values of an associative array, you could use a foreach loop, like this:

<?php
$detail = array("name" => "Anna", "course" => "SI664");

foreach($detail as $k => $v ) {
    echo "Key=",$k," Val=",$v,"\n";
}
?>

3. Multidimensional array

A multidimensional array is an array containing one or more arrays.

$products = array(
'paper' => array(
'copier' => "Copier & Multipurpose",
'inkjet' => "Inkjet Printer",
'laser' => "Laser Printer",
'photo' => "Photographic Paper"),
'pens' => array(
'ball' => "Ball Point",
'hilite' => "Highlighters",
'marker' => "Markers"),
'misc' => array(
'tape' => "Sticky Tape",
'glue' => "Adhesives",
'clips' => "Paperclips")
);

echo $products["pens"]["marker"];
// Output: Markers

II. Array Functions

  • array_key_exists($key, $ar) - Returns TRUE if key is set in the array
  • isset($ar[‘key’]) - Returns TRUE if key is set in the array
  • count($ar) - How many elements in an array
  • is_array($ar) - Returns TRUE if a variable is an array
  • sort($ar) - Sorts the array values (loses key)
  • ksort($ar) - Sorts the array by key
  • asort($ar) - Sorts array by value, keeping key association
  • shuffle($ar) - Shuffles the array into random order