# 太空飞船操作符（<=>）

## 目录：

* 简介
* 整型比较
* 字符串比较
* 数组比较
* 资料
* usort 场景示例

## 简介：

太空飞船操作符在比较变量时非常有用，这里说的变量包括标量类型（字符串型、整型、浮点型等）、，数组、对象。这个操作符相当于把三个比较符（`== 、 < 、 >`）融合成一个。

比如说使用场景可以用于 usort 、uasort 、uksort 的回调函数。具体使用规则如下：

* 当符号两边相等时返回 0
* 当符号右边大于符号左边时返回 -1
* 当符号左边大于符号右边时返回 1

## 整型比较：

例子：

```php
<?php
$intA = 1;
$intB = 2;
$intC = 1;

echo '整型比较:<br>';

echo $intA <=> $intC; // 返回 0
echo '<br>';

echo $intA <=> $intB; // 返回 -1
echo '<br>';

echo $intB <=> $intC; // 返回 1
```

执行结果：

```
整型比较:
0
-1
1
```

## 字符串比较：

例子：

```php
<?php
echo '字符串比较:<br>';

echo 'PHP 7' <=> 'PHP 7'; //返回 0
echo '<br>';

echo 'a' <=> 'b'; // 返回 -1
echo '<br>';

echo 'z' <=> 'x'; // 返回 1
```

执行结果：

```
字符串比较:
0
-1
1
```

## 数组比较：

```php
<?php
echo '数组比较:<br>';
echo [1,2,3] <=> [1,2,3]; // 0
echo "<br>";
echo [1,2,3] <=> [3,2,1]; // -1
echo "<br>";
echo [3,2,1] <=> [1,2,3]; // 1
```

执行结果：

```
数组比较:
0
-1
1
```

## 对象比较:

```php
<?php
// Objects
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 0
$a = (object) ["a" => "b"]; 
$b = (object) ["a" => "c"]; 
echo $a <=> $b; // -1
$a = (object) ["a" => "c"]; 
$b = (object) ["a" => "b"]; 
echo $a <=> $b; // 1
$a = (object) ["a" => "b"]; 
$b = (object) ["b" => "b"]; 
echo $a <=> $b; // 0
```

## usort 场景示例：

```php
<?php
// 老的 if 方式比较
function normal_sort($a, $b) : int
{
    if($a == $b) {
        return 0;
    } elseif ($a < $b) {
        return -1;
    } else {
        return 1;
    }
}

// 新的太空飞船操作符比较
function space_sort($a, $b) : int
{
    return $a <=> $b;
}

$normalArray = [1,34,56,67,98,45];

usort($normalArray, 'normal_sort');

foreach($normalArray as $k => $v) {
    echo $k.' => '.$v.'<br>';
}

//SpaceShip example
$sarray = [1,34,56,67,98,45];

usort($sarray, 'space_sort');

foreach($sarray as $key => $value) {
    echo $key.' => '.$value.'<br>';
}
```

以上代码if条件判断比较的方式，采用太空操作符一行搞定！输出结果:

```php
0 => 1
1 => 34
2 => 45
3 => 56
4 => 67
5 => 98
0 => 1
1 => 34
2 => 45
3 => 56
4 => 67
5 => 98
```

## 资料：

[php官方wiki 太空飞船操作符示例](https://wiki.php.net/rfc/combined-comparison-operator)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://php7.shujuwajue.com/php-70x-xin-te-xing/xin-zeng-cao-zuo-fu/tai-kong-fei-chuan-cao-zuo-fu-ff083c3d3e-ff09.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
