0
0
PHPprogramming~20 mins

Ternary operator in PHP - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Ternary Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
What is the output of this PHP code using ternary operator?
Consider the following PHP code snippet. What will it output?
PHP
<?php
$score = 75;
$result = $score >= 60 ? 'Pass' : 'Fail';
echo $result;
?>
AError
BFail
C75
DPass
Attempts:
2 left
💡 Hint
Check the condition before the question mark and what happens if true or false.
Predict Output
intermediate
2:00remaining
What does this nested ternary operator output?
Analyze the output of this PHP code with nested ternary operators.
PHP
<?php
$age = 20;
$status = $age < 13 ? 'Child' : ($age < 20 ? 'Teen' : 'Adult');
echo $status;
?>
AAdult
BTeen
CChild
DError
Attempts:
2 left
💡 Hint
Check each condition from left to right carefully.
🔧 Debug
advanced
2:00remaining
What error does this PHP ternary code produce?
Identify the error caused by this PHP code snippet.
PHP
<?php
$value = 10;
$result = $value > 5 ? 'High' 'Low';
echo $result;
?>
AParse error: syntax error
BOutputs 'HighLow'
COutputs 'High'
DUndefined variable error
Attempts:
2 left
💡 Hint
Check the syntax around the ternary operator carefully.
Predict Output
advanced
2:00remaining
What is the output of this PHP code with ternary and assignment?
What will this PHP code print?
PHP
<?php
$a = 0;
$b = $a ?: 5;
echo $b;
?>
A0
BError
C5
Dnull
Attempts:
2 left
💡 Hint
The ?: operator returns the left value if it is truthy, otherwise the right value.
🧠 Conceptual
expert
2:00remaining
How many items are in the resulting array after this PHP code?
What is the count of elements in the array produced by this code?
PHP
<?php
$array = [
  'a' => 1,
  'b' => 2,
  'c' => 3
];
$result = [];
foreach ($array as $key => $value) {
  $result[$key] = $value > 1 ? $value * 2 : $value;
}
echo count($result);
?>
A2
B3
C1
D0
Attempts:
2 left
💡 Hint
The foreach loop adds one element per original array item.