Sunday, November 18, 2012

Array at PHP part 1

Array is a collection of some of the data stored in a variable.  Each data in array has a index as a
identifier. Array can accommodate more than one value. Each member of array is referred to as elements.
For example we want to save brand name of  motorcycle into the variable $brand_motor. There are 4 brand name they are Honda, Yamaha, Suzuki and Kawasaki. Let's see illustration of variable $brand_motor  below.




Every value in elemets variable $brand_motor above can be accessed or called use index. There are 2 kinds of index, in the use of PHP they are:
1. Index Numeric=  use a number to mark an array element.
2. Index Associative= give a name to mark an array element.


Array Initialization

1. Index Numeric

Initialization array with index numeric can be done with way below.

         $brand_motor= array ( "Honda", "Yamaha", "Suzuki", "Kawasaki" );

or

         $brand_motor [ ]= "Honda" ;
         $brand_motor [ ]= "Yamaha" ;
         $brand_motor [ ]= "Suzuki" ;
         $brand_motor [ ]= "Kawasaki" ;


Above is automatic way because index is defined automatically by program. Below is a manual way because we defined index manually. Let's see...

         $brand_motor [0]= "Honda" ; 
         $brand_motor [1]= "Yamaha" ;
         $brand_motor [2]= "Suzuki" ;
         $brand_motor [3]= "Kawasaki" ;


Below is illustration of variable $brand_motor.

In PHP to display all the elements and values ​​from an array, we use print_r(). Let's see example below.


Click show to see and copy this code

Below is output.




2. Index Associative

Initialization array with index associative can be done with way below.

             $brand_motor= array ( "motor_1"=>"Honda",
                                               "motor_2"=> "Yamaha",
                                               "motor_3"=>"Suzuki",
                                               "motor_4"=>"Kawasaki" );


or

             $brand_motor ['motor_1']= "Honda" ;
             $brand_motor ['motor_2']= "Yamaha" ;
             $brand_motor ['motor_3']= "Suzuki" ;
             $brand_motor ['motor_4']= "Kawasaki" ;


Below is illustration of variable $brand_motor above. 


Let's see example below.


Click show to see and copy this code


Below is output.



Let's see reed more to Array at PHP part 2 here.


No comments:

Post a Comment