Array in PHP tutorial

Array is a special variable which can store multiple value. ( Note : a normal variable can store only one value at a time ). Arrays are the oldest and most important data structure which can hold multiple values. Each value in an array is associated with a key. And we can retrieve each value from array using the keys.

Arrays can be mainly two types

  • One-dimensional arrays
  • Multidimensional arrays

Array in PHP can be categorized as

  • Numeric arrays
  • Associative array
  • Multidimensional array

In PHP array can be declared using the construct array()

Numeric arrays are with a numeric index. Here we don’t need specify the keys. Index will start from 0. Means first data can be accessed using the index 0 , second data can be accessed using the index 1 etc
See the Example for a numeric array declaration
$names=array(“Syam”,”Binu”,”Bob”,”cathy”);
Its same as the following declarations
$names[0]=”Syam”;
$names[1]=”Binu”;
$names[2]=”Bob”;
$names[3]=”cathy”;

In Associative arrays each key is associated with a value.Here we need to specify each key and its associated value. And these values can be fetched using the declared keys.
See the example of an Associative array declaration
$age = array(“Syam”=>30, “Binu”=>25, “Bob”=>50, “cathy”=>30);
Here Syam, Binu etc are the keys and values are associated with those keys using => .
In this example we are trying to store the ages of some persons using arrays. So if we want to know the age of one particular person , we only need to know his name ( key ).
The above array can be declared same as
$age[“Syam”]=30;
$age[“Binu”]=25;
$age[“Bob”]=50;
$age[“cathy”]=30;

In Multidimensional arrays each element in array can be another array. Its useful for building matrices, tree and table like data storage structures.In some programming scenarios we can avoid the usage of several different one-dimensional arrays using a single Multidimensional arrays for our programming optimization , speed and other things.

For example , consider a case we need to store names , age and location. We can use a multidimensional array. See below
$data=array (“Syam”=>array(“age”=>30,”location”=>”India”),
“Bob”=>array(“age”=>50,”location”=>”USA”) );

Here is a sample program of array in PHP ( using the above array )

<?php
$data=array ("Syam"=>array("age"=>30,"location"=>"India"),"Bob"=>array("age"=>50,"location"=>"USA")  );
echo $data["Bob"]["location"];
?>

Its output will be ;
USA

Share

One thought on “Array in PHP tutorial”

  1. Arrays are for storing the data temporary only , when we leave the script data in array automatically deleted in the server… That’s why we use database tables for permanent storage of data .

Comments are closed.

Share
Share