Range Over Built in PHP

Let’s translate the provided Go code to PHP:

Here we use foreach to iterate over elements in a variety of built-in data structures. Let’s see how to use foreach with some of the data structures we’ve already learned.

PHP Code

<?php

// Here we use `foreach` to sum the numbers in an array.
$nums = [2, 3, 4];
$sum = 0;

foreach ($nums as $num) {
    $sum += $num;
}
echo "sum: $sum\n";

// `foreach` on arrays provides both the index and value for each entry. 
// Sometimes we actually want the indexes though.
foreach ($nums as $i => $num) {
    if ($num == 3) {
        echo "index: $i\n";
    }
}

// `foreach` on associative arrays (maps) iterates over key/value pairs.
$kvs = ["a" => "apple", "b" => "banana"];
foreach ($kvs as $k => $v) {
    printf("%s -> %s\n", $k, $v);
}

// `foreach` can also iterate over just the keys of a map.
foreach (array_keys($kvs) as $k) {
    echo "key: $k\n";
}

// `foreach` on strings iterates over characters.
$str = "go";
for ($i = 0; $i < strlen($str); $i++) {
    echo "$i " . ord($str[$i]) . "\n";
}
?>

Explanation

  1. Sum the numbers in an array

    • We create an array $nums with integers 2, 3, and 4.
    • We use foreach to iterate over each number in the array and calculate the sum.
    • The total sum is printed.
  2. Get the index and value from the array

    • We use foreach with both key and value to find the index of a specific value.
    • If the number is 3, the index is printed.
  3. Iterate over key/value pairs in an associative array

    • We create an associative array $kvs with some key-value pairs.
    • Using foreach, each key-value pair is printed.
  4. Iterate over just the keys of an associative array

    • We use array_keys to get the keys and iterate over them to print each key.
  5. Iterate over characters in a string

    • We use a for loop to iterate over each character in the string “go”.
    • The character’s index and its ASCII value (using ord function) are printed.

To run the program, save it as range_over_built_in_types.php and execute it using PHP.

$ php range_over_built_in_types.php
sum: 9
index: 1
a -> apple
b -> banana
key: a
key: b
0 103
1 111

The output demonstrates how foreach and for loops can iterate over arrays, associative arrays, and strings in PHP.