Arrays In PHP

Introduction to Arrays : Array is a collection of key/value pairs. A key/index can be integer or string. Keys can be non-sequential. Values can be of dissimilar data type. Arrays are prefixed by '$'. No limit on number of elements.

#Example
$a[0]=100;
$a[10]="abc";
$a["xyz"]=200;

Array Initialization

array() function is used to initialize an array. Default indexes are integers and starts with 0. Key/value pair can be initialized using '=' operator. Assignment without subscript, initializes a new key/value pair at the next available index.
Note : Arrays can be initialized by explicit keys i.e. keyword 'array' followed by key value pairs in brackets.

#Valid example of Array Initialization
$myarray=array(10,20,30); 
$myarray[0]=10;
$myarray["abc"]=20;
$myarray[2]=10;
$myarray[0]=10;
$myarray[10]=20;
$myarray[]=30;    #index/key will be 11
#Initialization – Explicit keys
$myarray=array("class1"=>10, "class2"=> 20, "class3"=> 30);
$myarray=array(10=>100, "class2"=> 200, 300);   # index for 300 is 11 , highest numerical index + 1

Array of Arrays

A multidimensional array is an array that contains one or more arrays. PHP supports multidimensional arrays that are two, three, four, five or more levels deep. However, arrays more than three levels deep are difficult for most people to manage.

#Example
$Team=array(
            "India" => array("Sachin", "Dravid", "Ganguly", "Shewag"),
            "Australia"=>array("Hayden", "Ponting", "Warne")
            );
echo $Team["India"][0];         		#Sachin
echo $Team["India"][2];  		        #Ganguly
echo $Team["Australia"][0];		        #Hayden
echo $Team["India"];		                #Array

Array Function

Below are the PHP Array function which are commonly used.
1. print_r() : Function is used to print the array in readable format. Output format is as below:

#Syntax
Array( [key1]=>value1 [key2]=>value2…..)
#Example
$arrEg=array("India"=>"New Delhi", "Sri Lanka"=>"Colombo",
                    "Bangladesh"=>"Dhaka");
print_r($arrEg);

2. is_array() : Function can be used to verify if a variable is an array. Returns TRUE or FALSE.

#Example
$arrEg=array("India"=>"New Delhi", "Sri Lanka"=>"Colombo",
                    "Bangladesh"=>"Dhaka");
if( is_array($arrEg))     
	echo "Is array";

3. array_unshift() : Adds elements to the beginning of the array and returns the size of array.

#Example
$states=array("Delhi","Karnataka");
echo array_unshift($states,"Maharashtra");
print_r($states);
# Output: Maharashtra, Delhi, Karnataka

4. array_push() : Adds elements to the end of the array and returns the size of array.

#Example
$states=array("Delhi","Karnataka");
echo array_push($states,"Maharashtra");
print_r($states);
# Output: Delhi, Karnataka, Maharashtra

5. array_shift() : Removes elements from the beginning of the array and returns the removed element.

#Example
$states=array("Delhi","Karnataka");
echo array_shift($states,);	
print_r($states);  
#Output
Delhi Karnataka

6. array_pop() : Removes elements from the end of the array and returns the removed element.

#Example
$states=array("Delhi","Karnataka");
echo array_pop($states,);		
print_r($states);   
#Output
Karnataka Delhi

7. in_array() : Function is used to search an element into an array, returns TRUE if found and FALSE otherwise.

#Example
$find_element="Delhi";
$states=array("Delhi","Karnataka");
if(in_array($find_element,$states))
echo "Yes, it is present in array";
#Output
Yes, it is present in array

8. array_key_exists() : Used to search the existence of a key in an array, returns TRUE if found and FALSE otherwise.

#Example
$states=array("Delhi","Karnataka");
if(array_key_exists("Delhi",$states))
     echo "Yes, Delhi is a key in states array";
else
      echo "Not present";
#Output
Not present

Other Functions

Function Use
count() Returns number of elements in the array
array_keys() Can be used to fetch the keys present in the array
array_values() Returns all the values of the respective keys present in the passed array
array_count_values() Returns the values and the frequency of each value in form of an array
array_reverse() Rearranges the array elements in the reverse order
array_flip() Is used to convert the keys to values and values to keys
sort() Is used to sort the array

Array Traversal Functions

Arrays Traversal : We can traverse an indexed array using loop in PHP. We can loop through the indexed array in two ways. First using for loop and second using foreach.

Function Use
key() Used to fetch the key in the present position of the array
current() Returns the value of current key in the array
next() Returns the value of the key immediately after the current key (pointer location will also be moved)
prev() Returns the value of the preceding key
reset() Used to set the array pointer to the value of starting key
end() Used to set the array pointer to the value of last key
#Example
$arr=array('One'=>"Karnataka","Two"=>"Maharashtra","Three"=>"AP");
$nextVal=next($arr);
echo $nextval;		#Maharashtra
$prevVal=prev($arr);
echo $prevval;		#Karnataka 
$endVal=end($arr);
echo $endval;		#AP 
$firstVal=reset($arr);
echo $firstval;		#Karanataka