PHP

PHP Array


 

An array is like a list or a collection of similar types of items that are stored in a single variable. For example, we need to store 100 or more numbers than we only need one variable for storing all the numbers.

 

Example:

<?php
   // Without using array
   $place1 = "Mumbai";
   $place2 = "Delhi";
   $place3 = "Kolkata";
   // Using Array
   $places = array("Mumbai", "Delhi", "Kolkata");
?>

 

Advantages of Array

  • Optimal Code
  • Easy to Understand
  • Organized

 

There are mainly three types of arrays:

  • Indexed Array
  • Associative Array
  • Multidimensional Array

 

1. Indexed Array:

An indexed array is a type of array where each element is assigned a numeric index starting from 0. The index represents the position of the element in the array.

 

Example:

<?php
   // Long-way
   $family[0] = "Father";
   $family[1] = "Mother";
   $family[2] = "Son";
   $family[3] = "Daughter";
   // Short-hand
   $family = array("Father", "Mother", "Son", "Daughter");
   // accessing value
   echo "Family members: $family[0], $family[1], $family[2], $family[3]";
?>

 

2. Associative Arrays

Associative array is a collection of key-value pairs instead of using indexes.

 

Example:

<?php
   // Associative array
   $tour = array(
       "name" => "Raj",
       "age" => 26,
       "city" => "London"
   );
   // Accessing elements
   echo $person["name"]; // Outputs: Raj
   echo $person["age"];  // Outputs: 26
   echo $person["city"]; // Outputs: London
?>

 

OUTPUT:

 

3. Multidimensional Array

Multidimensional array is also known as array of arrays. A  multidimensional array in PHP is like a table with rows and columns. Instead of having a single list of items, each element in a multidimensional array can itself be another array.

 

Example:

<?php
   // Multidimensional array
   $team = array(
       array("rohit", 22, "kolkata"),
       array("raj", 27, "delhi"),
       array("wasif", 21, "patna")
   );
   // Accessing elements
   echo $team[0][0]; // Outputs - rohit
   echo $team[1][1]; // Outputs: 27
   echo $team[2][2]; // Outputs: patna
?>

 

Output: