0
0
PHPprogramming~10 mins

Spaceship operator in PHP - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Spaceship operator
Evaluate left expression
Evaluate right expression
Compare left and right
Return -1 if left < right
Return 0 if left == right
Return 1 if left > right
End
The spaceship operator compares two values and returns -1, 0, or 1 depending on whether the left value is less than, equal to, or greater than the right value.
Execution Sample
PHP
<?php
$result = 5 <=> 3;
echo $result;
?>
This code compares 5 and 3 using the spaceship operator and prints the result.
Execution Table
StepLeft ExpressionRight ExpressionComparisonResult
1535 > 31
2222 == 20
3141 < 4-1
4---End of comparisons
💡 All comparisons done, operator returns -1, 0, or 1 based on comparison
Variable Tracker
VariableStartAfter 1After 2After 3Final
resultundefined10-1varies per comparison
Key Moments - 3 Insights
Why does the spaceship operator return 1 when left is greater than right?
Because the operator is designed to return 1 when the left value is greater, as shown in execution_table row 1 where 5 > 3 returns 1.
What happens if both values are equal?
The operator returns 0, indicating equality, as shown in execution_table row 2 where 2 == 2 returns 0.
Can the spaceship operator be used with strings?
Yes, it compares strings lexicographically, returning -1, 0, or 1 just like with numbers.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the result when left is 1 and right is 4?
A-1
B1
C0
DUndefined
💡 Hint
Check execution_table row 3 where left=1 and right=4
At which step does the spaceship operator return 0?
AStep 1
BStep 3
CStep 2
DStep 4
💡 Hint
Look at execution_table row 2 where left and right are equal
If the left expression is less than the right, what does the spaceship operator return?
A0
B-1
C1
DIt throws an error
💡 Hint
See execution_table row 3 for left < right case
Concept Snapshot
Spaceship operator (<=>) compares two values.
Returns -1 if left < right.
Returns 0 if left == right.
Returns 1 if left > right.
Useful for sorting and comparisons.
Works with numbers and strings.
Full Transcript
The spaceship operator in PHP compares two values and returns -1, 0, or 1 depending on whether the left value is less than, equal to, or greater than the right value. For example, 5 <=> 3 returns 1 because 5 is greater than 3. When both values are equal, like 2 <=> 2, it returns 0. If the left value is less, like 1 <=> 4, it returns -1. This operator is useful for sorting and comparing values easily.