Complete the code to loop through the array and print each fruit.
<?php $fruits = ['apple', 'banana', 'cherry']; foreach ($fruits as [1]) { echo $fruit . "\n"; } ?>
The variable $fruit is used to represent each element in the array during the loop.
Complete the code to loop through the array with keys and values.
<?php $ages = ['Alice' => 25, 'Bob' => 30]; foreach ($ages as [1] => $age) { echo "$name is $age years old.\n"; } ?>
The key variable $name holds the names in the array, which are the keys.
Fix the error in the foreach loop to correctly print keys and values.
<?php $colors = ['red' => '#FF0000', 'green' => '#00FF00']; foreach ($colors as $color [1] $hex) { echo "$color: $hex\n"; } ?>
= instead of =>.-> or colon : which are incorrect here.The correct syntax to separate key and value in a foreach loop is =>.
Fill both blanks to create a dictionary of word lengths for words longer than 3 letters.
<?php $words = ['cat', 'house', 'dog', 'elephant']; $lengths = []; foreach ($words as $word) { if ([1]($word) [2] 3) { $lengths[$word] = strlen($word); } } ?>
count which works on arrays, not strings.< instead of > causing wrong filtering.Use strlen to get the length of the word and > to check if it is longer than 3.
Fill all three blanks to create an associative array with uppercase keys and values greater than 10.
<?php $data = ['a' => 5, 'b' => 15, 'c' => 20]; $result = []; foreach ($data as [1] => [2]) { if ([2] > 10) { $result[strtoupper([1])] = [2]; } } ?>
The key variable is $key, the value variable is $value, and the uppercase function uses the key $key.