Challenge - 5 Problems
Spaceship Operator Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
❓ Predict Output
intermediate2:00remaining
What is the output of this PHP code using the spaceship operator?
Consider the following PHP code snippet. What will it output?
PHP
<?php $a = 5; $b = 10; echo $a <=> $b; ?>
Attempts:
2 left
💡 Hint
The spaceship operator returns -1 if the left is less than the right.
✗ Incorrect
The spaceship operator (<=>) returns -1 when the left value is less than the right value. Here, 5 is less than 10, so it returns -1.
❓ Predict Output
intermediate2:00remaining
What does this PHP code output when comparing equal values?
Look at this PHP code using the spaceship operator. What will it print?
PHP
<?php $x = 7; $y = 7; echo $x <=> $y; ?>
Attempts:
2 left
💡 Hint
The spaceship operator returns 0 when both sides are equal.
✗ Incorrect
When both values are equal, the spaceship operator returns 0. Here, both $x and $y are 7.
❓ Predict Output
advanced2:00remaining
What is the output of this PHP code comparing a string and an integer?
Consider the following PHP code snippet. What will it output?
PHP
<?php $a = 'apple'; $b = 5; echo $a <=> $b; ?>
Attempts:
2 left
💡 Hint
When comparing a string to an integer, the string is converted to a number. 'apple' converts to 0.
✗ Incorrect
When one operand is a number and the other is a string, the string is converted to a number. 'apple' converts to 0, and 0 < 5, so the spaceship operator returns -1.
❓ Predict Output
advanced2:00remaining
What is the output of this PHP code comparing arrays with the spaceship operator?
Analyze this PHP code and determine its output.
PHP
<?php $arr1 = [1, 2, 3]; $arr2 = [1, 2, 4]; echo $arr1 <=> $arr2; ?>
Attempts:
2 left
💡 Hint
The spaceship operator compares arrays element by element.
✗ Incorrect
The spaceship operator compares arrays element-wise. Since 3 is less than 4 at the third element, it returns -1.
🧠 Conceptual
expert2:00remaining
What is the value of $result after this PHP code runs?
Given this PHP code, what is the value stored in $result?
PHP
<?php function compareValues(mixed $a, mixed $b): int { return $a <=> $b; } $result = compareValues(3.5, 3); ?>
Attempts:
2 left
💡 Hint
The spaceship operator works with floats and integers.
✗ Incorrect
3.5 is greater than 3, so the spaceship operator returns 1.