Macam Macam Array di Dalam PHP


      Array merupakan tipe data terstruktur yang berguna untuk menyimpan sejumlah data yang bertipe sama. Bagian yang menyusun array disebut elemen array, yang masing-masing elemen array dapat diakses tersendiri melalui index array. Index array dapat berupa bilangan integer maupun string.

a. Array Basic 


<?php
   $punakawan = array("Semar","Gareng","Petruk","Bagong"); 
   echo $punakawan[0]; 
   //Hasilnya Semar echo "<br>"; 
   echo $punakawan[3]; 
   // Hasilnya Bagong $punakawan[1]="Semar";
   $punakawan[2]="Gareng"; 
   $punakawan[3]="Petruk"; 
   $punakawan[4]="Bagong”; 
   echo $punakawan[3];
  // Hasilnya Petruk
?>

b. Numeric Array

<?php     /* First method to create array. */      $numbers = array( 1, 2, 3, 4, 5);      foreach( $numbers as $value ) {            echo "Value is $value <br />"; } /* Second method to create array. */      $numbers[0] = "one";        $numbers[1] = "two";        $numbers[2] = "three";        $numbers[3] = "four";        $numbers[4] = "five";      foreach( $numbers as $value ) {  
         echo "Value is $value <br />";     }  ?>

c. Asosiatif Array

<?php 
/* First method to associate create array. */ 
$salaries = array( 
    "mohammad" => 2000, 
    "qadir" => 1000, 
    "zara" => 500 
); 
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />"; 
echo "Salary of qadir is ". $salaries['qadir']. "<br />"; 
echo "Salary of zara is ". $salaries['zara']. "<br />"; 
/* Second method to create array. */ 
$salaries['mohammad'] = "high";
$salaries['qadir'] = "medium"; 
$salaries['zara'] = "low"; 
echo "Salary of mohammad is ". $salaries['mohammad'] . "<br />"; 
echo "Salary of qadir is ". $salaries['qadir']. "<br />"; 
echo "Salary of zara is ". $salaries['zara']. "<br />"; 
?>
d. Multidimensional Array

<?php 
$marks = array( 
 "mohammad" => array ( 
   "physics" => 35, 
   "maths" => 30, 
   "chemistry" => 39 
  ), 
 "qadir" => array ( 
   "physics" => 30, 
   "maths" => 32, 
   "chemistry" => 29 
  ), 
 "zara" => array ( 
   "physics" => 31, 
   "maths" => 22,  
   "chemistry" => 39  
  )
); 
/* Accessing multi-dimensional array values */ 
echo "Marks for mohammad in physics : " ; 
echo $marks['mohammad']['physics'] . "<br />"; 
echo "Marks for qadir in maths : "; 
echo $marks['qadir']['maths'] . "<br />"; 
echo "Marks for zara in chemistry : " ; 
echo $marks['zara']['chemistry'] . "<br />"; 
?>

Macam Macam Array di Dalam PHP Rating: 4.5 Diposkan Oleh: Mambaur Roziq Alwi

No comments:

Post a Comment