0
0
PHPprogramming~10 mins

Array map function in PHP - Interactive Code Practice

Choose your learning style9 modes available
Practice - 5 Tasks
Answer the questions below
1fill in blank
easy

Complete the code to apply a function to each element of the array using array_map.

PHP
<?php
$numbers = [1, 2, 3, 4];
$squared = array_map([1], $numbers);
print_r($squared);
?>
Drag options to blanks, or click blank then click option'
Afn($n) => $n * $n
Bfunction square($n) { return $n + 1; }
Carray_sum
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using a function that does not return the squared value.
Passing a function name as a string without defining it.
2fill in blank
medium

Complete the code to convert all strings in the array to uppercase using array_map.

PHP
<?php
$words = ['apple', 'banana', 'cherry'];
$uppercased = array_map([1], $words);
print_r($uppercased);
?>
Drag options to blanks, or click blank then click option'
Astrtoupper
Btrim
Cstrlen
Dstrtolower
Attempts:
3 left
💡 Hint
Common Mistakes
Using strtolower which converts to lowercase instead.
Using strlen which returns string length, not the string itself.
3fill in blank
hard

Fix the error in the code to correctly double each number in the array using array_map.

PHP
<?php
$nums = [2, 4, 6];
$doubled = array_map([1], $nums);
print_r($doubled);
?>
Drag options to blanks, or click blank then click option'
Afunction($x) { return $x * 3; }
Bfunction double($x) { return $x + 2; }
Cfn($x) => $x * 2
Darray_sum
Attempts:
3 left
💡 Hint
Common Mistakes
Using a function that triples the number instead of doubling.
Using a function that adds 2 instead of multiplying.
4fill in blank
hard

Fill both blanks to create an array mapping each word to its length, but only for words longer than 3 characters.

PHP
<?php
$words = ['cat', 'elephant', 'dog', 'giraffe'];
$lengths = array_map([1], array_filter($words, fn($word) => strlen($word) [2] 3));
print_r($lengths);
?>
Drag options to blanks, or click blank then click option'
Astrlen
B<=
C>
Dcount
Attempts:
3 left
💡 Hint
Common Mistakes
Using <= instead of > in the filter condition.
Using count instead of strlen for string length.
5fill in blank
hard

Fill both blanks to create an array of uppercase words that have length less than 6.

PHP
<?php
$words = ['apple', 'banana', 'pear', 'kiwi', 'grape'];
$result = array_map([1], array_filter($words, fn($word) => strlen($word) [2] 6));
print_r($result);
?>
Drag options to blanks, or click blank then click option'
Astrtoupper
B<
C<=
Dstrtolower
Attempts:
3 left
💡 Hint
Common Mistakes
Using strtolower instead of strtoupper.
Using <= instead of < in the filter condition.