Range Over Built in PHP
On this page
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
Sum the numbers in an array
- We create an array
$numswith integers 2, 3, and 4. - We use
foreachto iterate over each number in the array and calculate the sum. - The total sum is printed.
- We create an array
Get the index and value from the array
- We use
foreachwith both key and value to find the index of a specific value. - If the number is 3, the index is printed.
- We use
Iterate over key/value pairs in an associative array
- We create an associative array
$kvswith some key-value pairs. - Using
foreach, each key-value pair is printed.
- We create an associative array
Iterate over just the keys of an associative array
- We use
array_keysto get the keys and iterate over them to print each key.
- We use
Iterate over characters in a string
- We use a
forloop to iterate over each character in the string “go”. - The character’s index and its ASCII value (using
ordfunction) are printed.
- We use a
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 111The output demonstrates how foreach and for loops can iterate over arrays, associative arrays, and strings in PHP.
Comments powered by Disqus