Title here
Summary here
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
// 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";
}
?>
Sum the numbers in an array
$nums
with integers 2, 3, and 4.foreach
to iterate over each number in the array and calculate the sum.Get the index and value from the array
foreach
with both key and value to find the index of a specific value.Iterate over key/value pairs in an associative array
$kvs
with some key-value pairs.foreach
, each key-value pair is printed.Iterate over just the keys of an associative array
array_keys
to get the keys and iterate over them to print each key.Iterate over characters in a string
for
loop to iterate over each character in the string “go”.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.