PHP ARRAY

Like another programming language php also having array. Array is a special variable which can used to store multiple values of same data type.

Array is used to hold all values under one single name and we used that value by referring that name of array. Array can be accessed by its index value.

Types of Array:

  1. Numeric Array
  2. Associative Array
  3. Multidimensional Array.
  • Numeric Array:  In numeric array store each element with a numeric index. There are generally two methods to create a numeric array:
  1.                 a) $computer = array(“Acer”,”Lenovo”,”deal”,”hp”);

In this the index value are automatically assigned to each array element starts from 0.

  1. b)$computer[0] = “Acer”;
  2. c)$computer[1] = “Lenovo”;
  3. d)$computer[2] = “deal”;
  4. e)$computer[3] = “hp”;

In this we assign the index value to each element in array.

Example:
[sourcecode language=”plain”]
<?php

$computer[0] =  “Acer”;

$computer[1] = “Lenovo”;

$computer[2] = “ deal”;

$computer[3] = “hp”;

Echo $computer[0].”and”.$computer[1].”are cheap and best”;

?>
[/sourcecode]
Output: Acer and Lenovo are cheap and best.

  • Associative Array: In this each id is associative with a value.

Numeric array is not best in storing data about specific named so we can use associative array. With associative array we can use the value as key and assign to them.

Example :
[sourcecode language=”plain”]
$employee = array (“Ram”=>23,”Sham”=>24,”Pankaj”=>23);

Or

$employee [‘Ram’] =”23”;

$employee [‘Sham’] = “24”;

$employee [‘Pankaj’] = “23”;

<strong>Example :</strong>

&lt;?php

$employee [‘Ram’] =”23”;

$employee [‘Sham’] = “24”;

$employee [‘Pankaj’] = “23”;

echo “Ram is”.$employee[‘Ram’].”Year old”;

?&gt;
[/sourcecode]
Output: Ram is 23 year old.

  • Multidimensional Array.: In this an array element contain array or we can say that each element in the main array can also be an array. And each element in the sub-array can be an array.

Example:
[sourcecode language=”plain”]
Array

(

[kumar]=&gt; array

(

[0] =&gt;pankaj

[1]=&gt;amit

)

[singh]=&gt; array

(

[0]=&gt; sumit

)

)[/sourcecode]

Leave a Reply