Complete the code to apply a function to each element of the array using array_map.
<?php $numbers = [1, 2, 3, 4]; $squared = array_map([1], $numbers); print_r($squared); ?>
The array_map function applies the given function to each element of the array. Here, the arrow function fn($n) => $n * $n squares each number.
Complete the code to convert all strings in the array to uppercase using array_map.
<?php $words = ['apple', 'banana', 'cherry']; $uppercased = array_map([1], $words); print_r($uppercased); ?>
strtolower which converts to lowercase instead.strlen which returns string length, not the string itself.The strtoupper function converts strings to uppercase. Using it with array_map applies this to each element.
Fix the error in the code to correctly double each number in the array using array_map.
<?php $nums = [2, 4, 6]; $doubled = array_map([1], $nums); print_r($doubled); ?>
The arrow function fn($x) => $x * 2 correctly doubles each number. Other options either triple, add 2, or are invalid here.
Fill both blanks to create an array mapping each word to its length, but only for words longer than 3 characters.
<?php $words = ['cat', 'elephant', 'dog', 'giraffe']; $lengths = array_map([1], array_filter($words, fn($word) => strlen($word) [2] 3)); print_r($lengths); ?>
count instead of strlen for string length.The array_filter keeps words with length greater than 3 using strlen($word) > 3. Then array_map applies strlen to get their lengths.
Fill both blanks to create an array of uppercase words that have length less than 6.
<?php $words = ['apple', 'banana', 'pear', 'kiwi', 'grape']; $result = array_map([1], array_filter($words, fn($word) => strlen($word) [2] 6)); print_r($result); ?>
strtolower instead of strtoupper.The array_filter keeps words with length less than 6 using strlen($word) < 6. Then array_map applies strtoupper to convert them to uppercase.