Introduction To Arrays In Php

What Is An Array

Arrays are special kind of variables that can stores multiple values at a time. If you have list of items you will store the values some thing like this.

$value1 = "america";
$value2 = "india";
$value3 = "canada";

This is quite cheap way to store values like this. You can store these values in a single variable to save your times by making so many variables or to remind it which variable was for india, america or canada. You can use array instead of simple variable to store multiple values.

Create Array In Php

It’s very simple to create an array in php.
Just type

array();

and your array will be ready to use.
In php there are about three types of array that you may use. And it depends upon your needs.

  • Indexed array – Array with numeric values
  • Associative array – Array with named keys
  • Multidimensional array – Array that contain one or more arrays

1. Indexed Arrays

You can make indexed arrays in two ways.

Assign values Automatically

You can assign values automatically in an array with the following code

$data = array("red",
              "yellow",
              "pink",
              "black");

Assign Values Manually

You can also assign values manually.

$data[0] = "pen";
$data[1] = "pencil";
$data[2] = "rubber";
$data[3] = "pointer";

Example

A very neat and clear example to use an indexed array just assign some values like this and print it in the same way like this.

$data = array('home','dinner','sleep');
echo "I want to go ".$data[0].".And then i'll have ".$data[1]."
      And then i will" .$data[2];

2. Associative Arrays

Same as indexed array we are also having twice ways to create associative arrays.
We can assign values directly making an array and input some values in it like that.

$data = array("name"=>"John",
              "age"=>"37",
              "location"=>"US");

OR simply we can create it by assigning values individually like this.

$data['name'] = "john";
$data['age'] = "37";
$data['location'] = "US";

Example:

$data = array("name"=>"john", "age"=>"37", "location"=>"US");
echo "My name is".$data['name']."my age is".$data['age']."
     And i lives in ".$data['location'];

3. Multidimensional Arrays

Third kind of array in php is multidimensional array. This is also quite simple. Just remind that any array that contains another array one or two or more will be your multidimensional array. Let’s make an example of it.

Example:

$data = array(
             array("john","US"),
             array("amanda","AUS")
              );

// For john we will write

echo "My name is".$data[0][0]."
      And i lives in".$data['0']['1'];

// For Amanda we will write

echo "My name is".$data[1][0]."
     And i lives in".$data['1']['1'];