Bird
0
0

You have an array $words = ['one', '', 'three', null, 'five'];. You want to join only the non-empty, non-null elements with a comma. Which code correctly does this?

hard📝 Application Q15 of 15
PHP - String Functions
You have an array $words = ['one', '', 'three', null, 'five'];. You want to join only the non-empty, non-null elements with a comma. Which code correctly does this?
A$filtered = array_filter($words); echo implode(', ', $filtered);
Becho implode(', ', $words);
C$filtered = array_map(trim, $words); echo implode(', ', $filtered);
D$filtered = array_filter($words, fn($w) => $w !== ''); echo implode(', ', $filtered);
Step-by-Step Solution
Solution:
  1. Step 1: Remove empty and null elements using array_filter

    array_filter without callback removes falsy values like empty string and null.
  2. Step 2: Use implode to join filtered array with comma

    Joining filtered elements with ', ' produces the desired string.
  3. Final Answer:

    $filtered = array_filter($words); echo implode(', ', $filtered); -> Option A
  4. Quick Check:

    array_filter removes empty/null, then implode joins [OK]
Quick Trick: Filter falsy values before implode to exclude empties [OK]
Common Mistakes:
  • Using implode directly without filtering
  • Using array_map(trim) which doesn't remove null
  • Filtering only empty strings but not null

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes