Back to questions
JuniorTheoryCommon
What does the program print?
<?php
$nums = [5, 8, 1, 6];
$even = array_filter($nums, fn($n) => $n % 2 === 0);
echo json_encode($even), ' ', json_encode(array_values($even)), "\n";{"1":8,"3":6} [8,6]
- Expecting
array_filterto renumber the values it keeps: it keeps their original keys, so the even numbers of[5, 8, 1, 6]sit under keys1and3andjson_encodewrites an object. - Expecting the function to pick what to drop:
array_filterkeeps every value for which the function returnstrueand drops the rest.
- What does
array_filterkeep when you call it without a function? - Why can a frontend receive a JSON object instead of an array after a filter?