Array in  php

Array  is  a collection of heterogeneous elements.

PHP is loosely typed  language, hence  in this way , we can store any type of value in array.

Array is collection of elements  where each element is a combination of key   and value .

   By default , first element key starts with  key ‘0’.

Difference between a variable and array is variable can  store single value where as an  array can  store collection of values.

By using print_r  function , we  can print all elements of array.

Example

 

<?php
 $sno=array(10,20,40,50);
Print_r($sno);  // print all elements of  array.
Echo $sno[1];   //    prints only one element with key.
?>

 

Output:   

Array ( [0] => 10 [1] => 20 [2] => 40 [3] => 50 ) 20

 

<?php
$sno=array(5,100=>10,20,50,50=>30, “codelack”);
Print_r($sno);
?>

 

Output:   

Array ( [0] => 5 [100] => 10 [101] => 20 [102] => 50 [50] => 30 [103] => “codelack” )

 

<?php
$arr=array(10,20, 0=>30);
Print_r($arr);
?>

 

Output:   

Array ( [0] => 30 [1] => 20 )

 

<?php
$arr = array();
$arr[0]=10;
$arr[1]=20;
$arr[2]=40;
Print_r($arr);
?>

 

Output:   

Array ( [0] => 10 [1] => 20 [2] => 40 )

 

Array elements are of two types:
  1.  Numeric elements : Elements with number key comes under numeric elements.
  2. Associative elements :  Elements with string key comes under associative elements.

 

Example
<?php
$arr = array();
$arr[0]=10;
$arr[‘hr’]=”codelack”;
$arr[‘admin’]=’BBB’;
Print_r($arr);
?>

 

Output:   

Array ( [0] => 10 [‘hr’] => ”codelack” [‘admin’] => ’BBB’ )