0
0
PHPprogramming~20 mins

Boolean type behavior in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Boolean Mastery in PHP
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2: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 ';
}
?>
Afalse true true true false false false false true
Bfalse true false false false false false false true
Cfalse true true false false false false false true
Dfalse true true false true false false false true
Attempts:
2 left
💡 Hint
Remember how PHP treats strings and arrays when cast to boolean.
Predict Output
intermediate
2: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');
?>
Abool(true) bool(true) bool(true) bool(false)
Bbool(false) bool(true) bool(true) bool(false)
Cbool(true) bool(false) bool(true) bool(false)
Dbool(true) bool(true) bool(false) bool(false)
Attempts:
2 left
💡 Hint
Loose equality in PHP converts types before comparing.
🔧 Debug
advanced
2: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";
}
?>
ABecause the code is correct and it should print "Yes", so the problem is elsewhere
BBecause the variable $value is an integer and cannot be compared to boolean
CBecause the code uses == instead of ===, causing unexpected type coercion
DBecause == compares values loosely and 1 is not equal to true
Attempts:
2 left
💡 Hint
Test the code by running it and see what it prints.
📝 Syntax
advanced
2:00remaining
Boolean expression syntax error
Which option will cause a syntax error in PHP?
Aif ($a && $b) { echo 'Yes'; }
Bif ($a &&) { echo 'Yes'; }
Cif ($a & $b) { echo 'Yes'; }
Dif ($a and $b) { echo 'Yes'; }
Attempts:
2 left
💡 Hint
Look for incomplete boolean expressions.
🚀 Application
expert
2: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;
?>
A8
B7
C5
D6
Attempts:
2 left
💡 Hint
Recall which values PHP treats as false.