Introduction to PHP – Getting to Know Arrays Part 3

Guest Posts Paolo Nikko Nuñal

In part 2 of our tutorial with arrays we talked about how to loop through an array and its indexes with for and foreach loops. This time around you'll be learning with PHP Associative Arrays. In which named keys are used in assigning the contents.

There are two ways to create an associative array the first one is through:

<?php
    $familyReese = array("John"=>"Father","Carla"=>"Mother","Jake"=>"Son");
?>


And the other one is through this.

<?php
   $familyReese['John'] = "Father";
   $familyReese['Carla'] = "Mother";
   $familyReese['Jake'] = "Son";
?>


In which they can be used in the PHP script by calling their names.

<?php
   echo "John is the ".$familyReese['John']." of the Reese family";
?>


Here's how you loop through all of them.

<?php
    $familyReese = array("John"=>"Father","Carla"=>"Mother","Jake"=>"Son");
    
    foreach($familyReese as $x=>$x_value)
    {
           echo $x. "is the ".$x_value;
    }
?>


Associative arrays are useful in passing values from one function to another. And as well as keeping your code clean and easy to understand. This is also used in inserting database. In which each key is different and can be used as the named of the values, name of the table, database or just about everything.