Php: ARRAY Tips & Tricks

What is an Array?

An array is a like a list or a group of similar elements which stores data of a specific data type. These data elements are stored in a series inside the array and each of these stored data element has its own position in the Array by which it is referred to and retrieved. The position of these stored elements is maintained by the Index of the Array which is usually made up of consecutive integers beginning at zero. The values which are used to index the elements in an array are unique. That means, you can have only one unique value as an indexer (Key) and no two data elements in an array will have same indexer or the key.

Types of Arrays in PHP

Numerical or an Indexed Array, the indexer of the array which is used to determine the position (also known as Key) of the stored data element is an integer which begins at zero.

Position in     Array Name
        0 => TCP
        1 => IP
        2 => DNS

Associative array, the key or the indexer of the array which is used to refer to the data element is a string and not an integer.

Abbreviation     Expanded Term
      TCP    =>    Transmission Control Protocol
         IP    =>     Internet Protocol
       DNS  =>     Dynamic Naming System

Multidimensional arrays can become confusing, as they are more complex than numerical and associative arrays. Think of multidimensional arrays as a book. Each array is a chapter and a “subarray” is a page number within that chapter. Remember, a multidimensional array can contain more than one array within itself.

An example of a multidimensional array can look like:

$colors = array(
             array(“black”, gallons , quarts , liters),
             array(“white”, gallons , liters),
             array(“yellow”, gallons , quarts , liters)

To associate a multidimensional array as a book, the array “colors” is the name of the book. The arrays “black”, “white” and “yellow” are chapters in the book, and “gallons”, “quarts” and “liters” represent page numbers within each chapter.

Notice that each subarray can have its own values which do not have to be the same as other subarrays. Also, each value within a subarray ends with a comma except the last value within the subarray. This is important to keep in mind, otherwise this multidimensional array will not work.

 $myLists['colors'] = array("apple"  => "red",
                            "grass"  => "green",
                            "sky"    => "blue",
                            "night"  => "black",
                            "wall"   => "white");                      
  $myLists['cars'] = array("BMW"     => "M6",
                           "Mercedes"=> "E 270 CDI",
                           "Lexus"   => "IS 220d",
                           "Mazda"   => "6",
                           "Toyota"  => "Avensis");                      

//To access and display an element in the multidimensional array 
//you just extend the key list as follows:

echo $myLists['cars']['Toyota'];

Array Operations in PHP

Split an array into chunks

To split an array into smaller chunks or smaller sized arrays, we use array_chunk() function of PHP. This will return arrays of several smaller sizes and each array's index number will start with zero unless you want to use the preserve_keys parameter to preserve the original index numbers from the input array used.

$my_array = array("One", "Two", "Three", "Four");
$split_array = array_chunk($my_array, 2);

    [0] => Array
            [0] => One
            [1] => Two

    [1] => Array
            [0] => Three
            [1] => Four


Combine an array with data elements and other with its keys

We can create an array by combining one array with keys and second array with corresponding data elements. Note that the number of keys and data elements in both the arrays has to be equal for this operation to be successful. We will make use of built-in function array_combine().

$keys_array = array(1,2,3,4);
$data_array = array("one","two","three","four");
$new_array = array_combine($keys_array, $data_array);


Array ( [1] => one [2] => two [3] => three [4] => four )

Merging two or more arrays

$first_array = array(1,2);
$second_array = array(3,4);
$third_array = array(5,6);

$merged_array = array_merge($first_array,$second_array,$third_array);


//Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 )

Searching for a value in an array

$months = array(1=>"Jan", "Feb", "Mar", "Apr", "May", "June", "July", "Aug",
                    "Sep", "Oct", "Nov", "Dec");

$key = array_search("May", $months); //Searching for May in months array

echo $key;
// We can also print the value that key points at

echo $months[$key];

//OUTPUT:  5 May

Find Value

in_array(search word, array) is a function very useful while working with arrays, especially for filtering certain items. Using this function you can find easily a value.

See the example:
$fruits = array("apple","orange","strawberry");

if(in_array("apple", $fruits))
    echo "Apple is in the array"
   echo "Apple is not in the array";

Validate if ARRAY

$yes = array('this', 'is', 'an array');

echo is_array($yes) ? 'Array' : 'not an Array';
echo "\n";

$no = 'this is a string';

echo is_array($no) ? 'Array' : 'not an Array';

Count Array
$fruits = array(1 => "apples",2 => "oranges",3 => "bananas");

$total_elements = count($fruits);


Get ODD and EVEN value of an Array

function odd($var)
    // returns whether the input integer is odd
    return($var & 1);

function even($var)
    // returns whether the input integer is even
    return(!($var & 1));

$array1 = array("a"=>1, "b"=>2, "c"=>3, "d"=>4, "e"=>5);
$array2 = array(6, 7, 8, 9, 10, 11, 12);

echo "Odd :\n";
print_r(array_filter($array1, "odd"));

echo "Even:\n";
print_r(array_filter($array2, "even"));


echo $string = '1|2,1|3,1|4';
$e = explode(',',$string);
$left = array();
$right = array();
foreach($e as $v){
 list($l,$r) = explode('|', $v);
$left[] = $l;
              $right[] = $r;

//---you can also do this
foreach($e as $v){
            list($left[],$right[]) = explode('|', $v);



Array ( [0] => 1 [1] => 1 [2] => 1 ) 
Array ( [0] => 2 [1] => 3 [2] => 4 )


Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

0 comments: on "Php: ARRAY Tips & Tricks"

:) ) ;) ) ;;) :D ;) :p :( ( :) :( :X =(( :-o :-/ :-* :| 8-} :) ] ~x( :-t b-( :-L x( =))
Post a Comment