Sunday, 9 June 2013

Array and Array Operations: PHP


Array creation:

To initialize an array in PHP:

$names_1  = array();   
                       
To add value to that array:

$names_1[] = "Bob";   
$names_1[] = "Marley";
$names_1[] = "Alex";
$names_1[] = "David";

You can also construct an array as follows:

            $arr1 = array(10,30,10,20,50);
           
To print the created array:

            print_r($names);


Array operations:
                       
To convert a string to array:

            You can use ‘explode’ to split an string with characters and add each element to array as below:

$names_2 = "Bob,Marley,Alex,David";
                       
$names_3 = explode("," , $names_2);   //--> String to array
print_r($names_3);                                                      
                       
To convert a array to string:

            If you want to get the elements from the array, and convert it into a string with each array elements separated by a character [say coma ‘,’], then you can make use of PHP ‘implode’.

print(implode(",",$names_1));               //--> Array to string
 
To eliminate similar data/elements from an array (array_unique):

$arr1 = array(10,30,10,20,50);

                       
$arr1 = array_unique($arr1);    //--> To eliminate similar data from the array
 print_r($arr1);
                       
To sort and reverse sort an array (sort and rsort):

            sort($arr1);                               //--> To sort an array
print_r($arr1);
                       
            rsort($arr1);                             //--> To reverse-sort an array
            print_r($arr1);

To add/ concatenate two arrays (array_merge):
                       
            $arr_1 = array(10,30,10,20,50);
            $arr_2 = array("Leon","CEO",41);
                       
            $arr_3 = array_merge($arr_1,$arr_2);  //--> To concatenate 2 arrays
            print_r($arr_3);

           
To get index key of an array as an array:

$arr_4 = array("name"=>" Leon ","destination"=>"CEO","age"=>41);
            print_r($arr_4);                        //--> Array with key index
            print_r(array_keys($arr_4));     //--> To get the index keys as an array


To check whether an element is in an array:

            $arr_5 = array("apple","orange","mango","grape","peach");
                       
            if(in_array("orange",$arr_5)){
     //--> To check whether an element is in an array
                        echo "Element Found...";
            }

No comments:

Post a Comment