Middle+
What is the output of the following code? <?php function format(&$item) { $item = strtoupper($item) . '.'; return $item; } $shopping = array("fish", "bread", "eggs", "jelly", "apples"); array_walk($shopping, "format"); $shopping = sort($shopping); echo $shopping[1]; A "BREAD." B nothing (no output) C "apples" D "fish" E "APPLES."
sobes.tech AI
Answer from AI
This code does the following:
- The
formatfunction takes an array element by reference, converts it to uppercase, and adds a period. array_walkapplies this function to all elements of the$shoppingarray, modifying them in place.- Then
sort($shopping)is called. Important: thesortfunction returns a boolean value (true/false), not a sorted array. - In the line
$shopping = sort($shopping);, the variable$shoppingis assigned the result ofsort, which istrue(1). - Then it tries to output
$shopping[1], but$shoppingis now a boolean value, not an array.
Therefore:
- The output will be empty (nothing will be printed), because
$shoppingis not an array.
Correct answer: B, nothing (no output).
If you fix the code by removing the assignment of the result of sort:
array_walk($shopping, "format");
sort($shopping);
echo $shopping[1];
Then the array will be sorted, and the second element of the sorted array with a period and in uppercase will be printed.