Challenge - 5 Problems
Boolean Mastery in PHP
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
Boolean evaluation of different values
What is the output of this PHP code snippet?
PHP
<?php $values = [0, 1, -1, "0", "false", "", null, [], [0]]; foreach ($values as $v) { echo (bool)$v ? 'true ' : 'false '; } ?>
Attempts:
2 left
💡 Hint
Remember how PHP treats strings and arrays when cast to boolean.
✗ Incorrect
In PHP, the following values are considered false when cast to boolean: 0, "0", empty string "", null, and empty array []. All other values are true.
So the outputs correspond to these evaluations.
❓ Predict Output
intermediate2:00remaining
Boolean comparison with loose equality
What is the output of this PHP code?
PHP
<?php var_dump(false == 0); var_dump(false == ''); var_dump(false == null); var_dump(false == 'false'); ?>
Attempts:
2 left
💡 Hint
Loose equality in PHP converts types before comparing.
✗ Incorrect
In PHP, false == 0, false == '', and false == null all evaluate to true because of type juggling. However, false == 'false' is false because 'false' is a non-empty string and converts to true in boolean context.
🔧 Debug
advanced2:00remaining
Unexpected boolean result in conditional
Why does this PHP code always print "No" even when $value is 1?
PHP
<?php $value = 1; if ($value == true) { echo "Yes"; } else { echo "No"; } ?>
Attempts:
2 left
💡 Hint
Test the code by running it and see what it prints.
✗ Incorrect
The code actually prints "Yes" because 1 == true evaluates to true in PHP. So the problem is not in this snippet.
📝 Syntax
advanced2:00remaining
Boolean expression syntax error
Which option will cause a syntax error in PHP?
Attempts:
2 left
💡 Hint
Look for incomplete boolean expressions.
✗ Incorrect
Option B has a syntax error because the && operator is missing the right operand.
🚀 Application
expert2:00remaining
Count how many values are true in mixed array
Given this PHP array, how many elements evaluate to true when cast to boolean?
PHP
<?php $items = [0, "", "0", null, false, true, 1, -1, [], [0], "false"]; $count = 0; foreach ($items as $item) { if ((bool)$item) { $count++; } } echo $count; ?>
Attempts:
2 left
💡 Hint
Recall which values PHP treats as false.
✗ Incorrect
False values are: 0, "", "0", null, false, and empty array []. All others are true.
Counting true values: true, 1, -1, [0], "false" → 5