Google News
logo
PHP Program to Spaceship Operators
In the following example of PHP program that demonstrates the use of the spaceship operator :
Program :
<?php

// Declare two arrays
$arr1 = array(1, 2, 3);
$arr2 = array(2, 3, 4);

// Sort using spaceship operator
usort($arr1, function($a, $b) {
    return $a <=> $b;
});
echo "Sorted array using spaceship operator: ";
print_r($arr1);

// Compare using spaceship operator
echo "Comparison using spaceship operator: ";
echo $arr1 <=> $arr2;

?>
Output :
Sorted array using spaceship operator: Array ( [0] => 1 [1] => 2 [2] => 3 )
Comparison using spaceship operator: -1
In this example, we have declared two arrays `$arr1` and `$arr2` and assigned them the values `(1, 2, 3)` and `(2, 3, 4)`, respectively.

We then use the spaceship operator `<=>` to sort `$arr1` in ascending order and compare it to `$arr2`.

Finally, we print out the sorted array and the comparison result using the `print_r` and `echo` statements.