This site is mobile accessible. Press the "Tap Here" button to use a different font-size.


Smartphone icons created by Freepik - Flaticon

4.1.2 Associative Arrays

    • Associative arrays are arrays that use named keys that you assign to them.
    • There are two ways to create an associative array:
    $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");

    or

    $age['Peter'] = "35";
    $age['Ben'] = "37";
    $age['Joe'] = "43";

    The named keys can then be used in a script:

    Example 1: PHP Arrays - Associative Arrays part 1
    <?php
    $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
    echo "Peter is " . $age['Peter'] . " years old.";
    ?>

    Associative arrays are arrays that use named keys that you assign to them.

    Example 2: PHP Arrays - Associative Arrays part 2
    $car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
    var_dump($car);

    Access Associative Arrays

    To access an array item you can refer to the key name.

    Example 3: PHP Arrays - Access Associative Arrays

    Display the model of the car:

    $car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
    echo $car["model"];

    Change Value

    To change the value of an array item, use the key name:

    Example 4: PHP Associative Arrays: Change Key Value

    Change the year item:

    $car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
    $car["year"] = 2024;
    var_dump($car);

    Loop Through an Associative Array

    To loop through and print all the values of an associative array, you could use a foreach loop, like this:

    Example 5: Associative Arrays - Loop Through an Associative Array part 1

    Display all array items, keys and values:

    $car = array("brand"=>"Ford", "model"=>"Mustang", "year"=>1964);
    
    foreach ($car as $x => $y) {
      echo "$x: $y <br>";
    }

    Another example

    Example 6: Associative Arrays - Loop Through an Associative Array part 2
    <?php
    $age = array("Peter"=>"35", "Ben"=>"37", "Joe"=>"43");
    
    foreach($age as $x => $x_value) {
      echo "Key=" . $x . ", Value=" . $x_value;
      echo "<br>";
    }
    ?>

    Complete PHP Array Reference

    Navigate this module

    Eventually the navigation links, above, will be replaced by these << (previous) and >> (next) buttons below.



    Animated PHP icons used in the buttons provided by ICONS8.COM. Smartphone icons created by Freepik - Flaticon

    Module 4 quiz