Hi, I'm Chandra Sekar M

Sub-Categories
Technology

Arrays in PHP

Arrays in PHP

An array can store multiple values in one variable.

Basic Variable Example :

<?php
$resultArray0 = "Apple";
$resultArray1 = "Ball";
$resultArray2 = "Cat";
echo "A for " . $resultArray0 . "<br/>";
echo "B for " . $resultArray1 . "<br/>";
echo "C for " . $resultArray2 . "<br/>";
?>

[or]

Array Variable Example :

<?php
$resultArray = array("Apple", "Ball", "Cat");
echo "A for " . $resultArray[0] . "<br/>";
echo "B for " . $resultArray[1] . "<br/>";
echo "C for " . $resultArray[2] . "<br/>";
?>


Types of Arrays in PHP

1) Numeric / Indexed arrays

2) Associative arrays

3) Multidimensional arrays


1) Numeric / Indexed arrays : We can create a indexed array in two ways, Find the example below,

a) $resultArray = array("Apple", "Ball", "Cat");    [or]   
 b) $resultArray[0] = "Apple";
    $resultArray[1] = "Ball";
    $resultArray[2] = "Cat";


if the values are dynamic and could not able to count manually then we can follow with Loop Indexed Array

<?php
$alpha = array("Apple", "Ball", "Cat", "Dog", "Elephant");  
$totalCount = count($alpha);
for($x=0; $x<$totalCount; $x++) {
    echo $cars[$x]."<br/>";
}
?>


2) Associative arrays : We can assign a value with Key into Array and it differentiate in to two ways. Find the Example below,

a) $resultArray = array("A"=>"Apple", "B"=>"Ball", "C"=>"Cat"); [or] 
b) $resultArray['A'] = "Apple";
   $resultArray['B'] = "Ball";
   $resultArray['C'] = "Cat";

3) Multidimensional arrays : It containing more than one array. find the example below,

<?php
         $Cars = array(
            "safari" => array (
               "color" => "Black",
               "price" => "6,00,000",
               "offer" => "10%"
            ),


            "swift" => array (
               "color" => "White",
               "price" => "8,00,000",
               "offer" => "7%"
            ),


            "zen" => array (
               "color" => "Gray",
               "price" => "12,00,000",
               "offer" => "12%"
            )
         );


         /* Print multi-dimensional array values */
         echo "Safari Show Room Price : " ;
         echo $marks['safari']['price'] . "<br />";


         echo "swift Show Room Price : ";
         echo $marks['swift']['price'] . "<br />";


         echo "zen Show Room Price : " ;
         echo $marks['zen']['price'] . "<br />";
      ?>

 

 

Subscribe to our Newsletter

Sign up for free and be the first to get notified about new posts.