Sobes.tech
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:

  1. The format function takes an array element by reference, converts it to uppercase, and adds a period.
  2. array_walk applies this function to all elements of the $shopping array, modifying them in place.
  3. Then sort($shopping) is called. Important: the sort function returns a boolean value (true/false), not a sorted array.
  4. In the line $shopping = sort($shopping);, the variable $shopping is assigned the result of sort, which is true (1).
  5. Then it tries to output $shopping[1], but $shopping is now a boolean value, not an array.

Therefore:

  • The output will be empty (nothing will be printed), because $shopping is 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.