PHP Arrays

Array is a variable, that contains collection of other values, available on specific indices. To access the value of array we need to specify the name of the array and the index of the data.

Structure of simple array and variable.



As you see, the difference between arrays and variables is not very big. Variable can take only one value while an array several.

Let's see an example :

<?php 
    $var[0] = "a";
    $var[1] = "y";
    $var[2] = "h";
    $var[3] = "e";
    $var[4] = "u";

    echo $name[2];
    // outout  h

?>

In this example, first of all we create the first element of the array with the index "0" and assign it a value of "a". Then, in the same way we create the other 4 array elements. Then using the echo statement we derive the third element of the array to the screen. As you can see, in order to bring the element of the array on the screen, we need to specify the name of the array and the index of the data.

In addition to the above method, an array in php we can create by using keyword array.

<?php
    $var = array (0 => "a", 1 => "y", 2 => "h", 3 => "e", 4 => "u");
    echo $name[2];
    // outout  h

?>

Also, we can create an array without setting indexes, PHP would set indexes automatically starting from zero .

<?php 
    $var[] = "a";
    $var[] = "y";
    $var[] = "h";
    $var[] = "e";
    $var[] = "u";

   // or 


   $var = array ( "a",  "y", "h","e", "u");
   
?>

Php support another form of arrays, Associative arrays . Difference from simple array, are indexes. If it in simple arrays are numeric indices, in the association they are strings .

Associative arrays are created in the same way .

<?php 
    $var["one"] = "a";
    $var["two"] = "y";
    $var["three"] = "h";
    $var["four"] = "e";
    $var["five"] = "u";

   // or 


   $var = array ("one"=> "a",  "two"=>"y", "three"=>"h", "four"=>"e", "five"=>"u");
   
   echo $var["three"];
   // output h


?>

Multidimensional Arrays . Create a multidimensional array is similar to creating an simple array. The difference is that each element of the multidimensional array as an array.

<?php 
   
   $cars = array(
               [0]=>array("model"=>"BMW", "color"=>"while", "engine"=>"3.0 L" ),
               [1]=>array("model"=>"AUDI", "color"=>"black", "engine"=>"2.5 L" ),
               [2]=>array("model"=>"TOYOTA", "color"=>"red", "engine"=>"2.0 L" )
);


   echo $cars[0]["model"];
   // output BMW


   echo $cars[1]["color"];
   // output black


   echo $cars[2]["engine"];
   // output 2.0 L

  

?>

Php has lot of functions for manipulate arrays, and we will learn about them in our next lessons.