Bird
0
0

You want to filter an array in PHP to keep only truthy values (non-empty, non-zero, etc.). Which code correctly uses boolean behavior to achieve this?

hard📝 Application Q15 of 15
PHP - Variables and Data Types
You want to filter an array in PHP to keep only truthy values (non-empty, non-zero, etc.). Which code correctly uses boolean behavior to achieve this?
$arr = [0, 1, "", "hello", false, true, null, [], [1]];
$filtered = array_filter($arr, function($v) {
    // What to put here?
});
print_r($filtered);
Areturn $v == true;
Breturn (bool)$v;
Creturn $v === true;
Dreturn !empty($v);
Step-by-Step Solution
Solution:
  1. Step 1: Understand array_filter callback

    The callback should return true for values to keep. Casting to (bool) returns true for all truthy values.
  2. Step 2: Compare options

    return (bool)$v; casts to boolean correctly. return $v == true; uses loose comparison which may include unwanted values. return $v === true; keeps only true boolean, excluding truthy values. return !empty($v); excludes some truthy values like true boolean but empty arrays are false.
  3. Final Answer:

    return (bool)$v; -> Option B
  4. Quick Check:

    Cast to bool to filter truthy values [OK]
Quick Trick: Use (bool) cast in filter callback to keep truthy values [OK]
Common Mistakes:
  • Using strict === true excludes truthy but non-true values
  • Using == true includes unwanted falsy values
  • Using empty() excludes some truthy values

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PHP Quizzes