Bird
0
0

How can you create an array of values from an associative array $arr but only include values whose keys start with the letter 'a'?

hard📝 Application Q9 of 15
PHP - Array Functions
How can you create an array of values from an associative array $arr but only include values whose keys start with the letter 'a'?
A$values = array_values(array_filter($arr, fn($k) => str_starts_with($k, 'a')));
B$values = array_values(array_filter($arr, fn($v, $k) => str_starts_with($k, 'a'), ARRAY_FILTER_USE_BOTH));
C$values = array_keys(array_filter($arr, fn($k) => str_starts_with($k, 'a')));
D$values = array_filter($arr, fn($v) => str_starts_with($v, 'a'));
Step-by-Step Solution
Solution:
  1. Step 1: Use array_filter with key and value

    Use ARRAY_FILTER_USE_BOTH to filter by keys and values, checking keys start with 'a'.
  2. Step 2: Extract values from filtered array

    Use array_values() to get only the values from the filtered array.
  3. Final Answer:

    $values = array_values(array_filter($arr, fn($v, $k) => str_starts_with($k, 'a'), ARRAY_FILTER_USE_BOTH)); -> Option B
  4. Quick Check:

    Filter by key then get values = $values = array_values(array_filter($arr, fn($v, $k) => str_starts_with($k, 'a'), ARRAY_FILTER_USE_BOTH)); [OK]
Quick Trick: Use ARRAY_FILTER_USE_BOTH to filter by keys and values [OK]
Common Mistakes:
  • Filtering only by values
  • Using array_keys instead of array_values
  • Ignoring ARRAY_FILTER_USE_BOTH flag

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes