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


Smartphone icons created by Freepik - Flaticon

4.1.1 Indexed Arrays

    • There are two ways to create indexed arrays:
    • The index can be assigned automatically (index always starts at 0), like this:
    $cars = array("Volvo", "BMW", "Toyota");

    or the index can be assigned manually:

    $cars[0] = "Volvo";
    $cars[1] = "BMW";
    $cars[2] = "Toyota";

    The following example creates an indexed array named $cars, assigns three elements to it, and then prints a text containing the array values:

    Example 1: PHP Arrays
    <?php
    $cars = array("Volvo", "BMW", "Toyota");
    echo "I like " . $cars[0] . ", " . $cars[1] . " and " . $cars[2] . ".";
    ?>

    Change Value

    To change the value of an array item, use the index number:

    Example 2: PHP Arrays - Change Value

    To change the value of an array item, use the index number:

    $cars = array("Volvo", "BMW", "Toyota");
    $cars[1] = "Ford";
    var_dump($cars);

    Loop Through an Indexed Array

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

    Example 3: Indexed Arrays - Loop Through an Indexed Array
    <?php
    $cars = array("Volvo", "BMW", "Toyota");
    $arrlength = count($cars);
    
    for($x = 0; $x < $arrlength; $x++) {
      echo $cars[$x];
      echo "<br>";
    }
    ?>

    Index Number

    • The key of an indexed array is a number, by default the first item is 0 and the second is 1 etc., but there are exceptions.
    • New items get the next index number, meaning one higher than the highest existing index.
    • So if you have an array like this:
    $cars[0] = "Volvo";
    $cars[1] = "BMW";
    $cars[2] = "Toyota";

    And if you use the array_push() function to add a new item, the new item will get the index 3:

    Example 4: PHP Arrays: Index Number part 1
    array_push($cars, "Ford");
    var_dump($cars);

    But if you have an array with random index numbers, like this:

    $cars[15] = "Volvo";
    $cars[7] = "BMW";
    $cars[14] = "Toyota";
    

    And if you use the array_push() function to add a new item, what will be the index number of the new item?

    Example 5: PHP Arrays: Index Number part 2
    array_push($cars, "Ford");
    var_dump($cars);

    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