Complete the code to count the number of elements in the array.
<?php $fruits = ['apple', 'banana', 'cherry']; $count = [1]($fruits); echo $count; ?>
The count() function returns the number of elements in an array.
Complete the code to get the length of the string stored in the array element.
<?php $words = ['hello', 'world']; $length = [1]($words[0]); echo $length; ?>
The strlen() function returns the length of a string in PHP.
Fix the error in the code to correctly count the elements in the array.
<?php $numbers = [1, 2, 3, 4]; $total = [1]($numbers); echo $total; ?>
length() which is not a PHP function.strlen() on arrays causes errors.The correct function to count array elements is count(). Using length or strlen causes errors.
Fill both blanks to create an associative array with word lengths for words longer than 3 characters.
<?php $words = ['cat', 'house', 'dog', 'elephant']; $lengths = []; foreach($words as [1]) { if(strlen([1]) > 3) { $lengths[[1]] = [2]; } } print_r($lengths); ?>
strlen('word') which returns length of the literal 'word', not the variable.In PHP, to create an associative array with keys and values, you use the syntax 'key' => value. Here, the key is the word itself, and the value is its length using strlen($word).
Fill all three blanks to create a filtered array of words longer than 4 characters with their lengths.
<?php $words = ['sun', 'moon', 'stars', 'sky']; $result = array_filter(array_map(function([1]) { return ['[2]' => [1], '[3]' => strlen([1])]; }, $words), function($item) { return $item['length'] > 4; }); print_r($result); ?>
The function parameter should be $word. The key for the word is 'word' and the key for length is 'length'. This creates an array of words with their lengths, then filters those longer than 4.