All categories
    PHPIntermediate

    PHP Arrays

    Work with PHP arrays: indexed arrays, associative arrays, looping with foreach, and helpful array functions like sort and array_sum.

    01Indexed arrays

    main.php
    <?php
    $nums = [10, 20, 30];
    echo $nums[0], "\n";
    echo count($nums), "\n";
    Output
    10
    3

    02Associative arrays

    main.php
    <?php
    $person = ["name" => "Ada", "age" => 36];
    echo $person["name"], "\n";
    echo $person["age"], "\n";
    Output
    Ada
    36

    03Loop with foreach

    main.php
    <?php
    $fruits = ["apple", "banana", "cherry"];
    foreach ($fruits as $fruit) {
        echo $fruit, "\n";
    }
    Output
    apple
    banana
    cherry

    04Array functions

    main.php
    <?php
    $nums = [3, 1, 4, 1, 5];
    echo array_sum($nums), "\n";
    echo max($nums), "\n";
    sort($nums);
    echo implode(",", $nums), "\n";
    Output
    14
    5
    1,1,3,4,5