官术网_书友最值得收藏!

New operators

PHP 7 introduced two interested operators. These operators can help write less and cleaner code, so the final code will be more readable as compared to the traditional operators in use. Let's have a look at them.

The Spaceship operator (<=>)

The Spaceship or Combined Comparison operator is useful to compare values (strings, integers, floats, and so on), arrays, and objects. This operator is just a wrapper and performs the same tasks as the three comparison operators ==, <, and >. This operator can also be used to write clean and less code for callback functions for usort, uasort, and uksort. This operator works as follows:

  • It returns 0 if both the operands on left- and right-hand sides are equal
  • It returns -1 if the right operand is greater than the left operand
  • It returns 1 if the left operand is greater than the right one

Let's take a look at a few examples by comparing integers, strings, objects, and arrays and note the result:

$int1 = 1;
$int2 = 2;
$int3 = 1;

echo $int1 <=> $int3; //Returns 0
echo '<br>';
echo $int1 <=> $int2; //Returns -1
echo '<br>';
echo $int2 <=> $int3; //Returns 1

Run the preceding code, and you will have an output similar to the following:

0
-1
1

In the first comparison, in which we compare $int1 and $int3, both are equal, so it will return 0. In the second comparison, in which $int1 and $int2 are compared, it will return -1 because the right operand ($int2) in greater than the left operand ($int1). Finally, the third comparison will return 1 as the left operand ($int2) is greater than the right operand ($int3).

The preceding is a simple example in which we compared integers. We can check strings, objects, and arrays in the same way, and they are compared the same standard PHP way.

Note

Some examples for the <=> operator can be found at https://wiki.php.net/rfc/combined-comparison-operator. This is an RFC publication that has more useful details about its usage.

This operator can be more useful in sorting arrays. Take a look at the following code:

Function normal_sort($a, $b) : int 
{
  if( $a == $b )
    return 0;
  if( $a < $b )
    return -1;
  return 1;
}

function space_sort($a, $b) : int
{
  return $a <=> $b;
}

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

//Sort the array in asc
usort($normalArray, 'normal_sort');

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

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

//Sort it by spaceship operator
usort($spaceArray, 'space_sort');

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

In the preceding code, we used two functions to sort the two different arrays with the same values. The $normalArray array is sorted by the normal_sort function, in which the normal_sort function uses if statements to compare the values. The second array $spaceArray has the same values as $normalArray, but this array is sorted by the space_sort function, which uses the Spaceship operator. The final result for both array sorts is the same, but the code in the callback functions is different. The normal_sort function has if statements and multiple lines of code, while the space_sort function has a single line of code—that's it! The space_sort function code is clearer and does not require multiple if statements.

The null coalesce operator(??)

We all know ternary operators, and we use them most of the time. Ternary operators are just a single-line replacement for if-else statements. For example, consider the following code:

$post = ($_POST['title']) ? $_POST['title'] : NULL;

If $_POST['title'] exists, then the $post variable will be assigned its value; otherwise, NULL will be assigned. However, if $_POST or $_POST['title'] does not exist or is null, then PHP will issue a notice of Undefined index. To fix this notice, we need to use the isset function, as follows:

$post = isset($_POST['title']) ? $_POST['title'] : NULL;

Mostly, it will seem fine, but it becomes very nasty when we have to check for values in multiple places, especially when using PHP as a templating language.

In PHP 7, the coalescence operator is introduced, which is simple and returns the value of its first operand (left operand) if it exists and is not null. Otherwise, it returns its second operand (right operand). Consider the following example:

$post = $_POST['title'] ?? NULL;

This example is exactly similar to the preceding code. The coalesce operator checks whether $_POST['title'] exists. If it does, the operator returns it; otherwise, it returns NULL.

Another great feature of this operator is that it can be chained. Here's an example:

$title = $_POST['title'] ?? $_GET['title'] ?? 'No POST or GET';

According to the definition, it will first check whether the first operand exists and return it; if it does not exist, it will return the second operand. Now, if there is another coalesce operator used on the second operand, the same rule will be applied, and the value on the left operand will be returned if it exists. Otherwise, the value of the right operand will be returned.

So, the preceding code is the same as the following:

If(isset($_POST['title']))
  $title = $_POST['title'];
elseif(isset($_GET['title']))
  $title = $_GET['title'];
else
  $title = 'No POST or GET';

As can be noted in the preceding examples, the coalesce operator can help write clean, concise, and less code.

主站蜘蛛池模板: 祁东县| 古交市| 会昌县| 胶南市| 秀山| 延吉市| 河池市| 旬邑县| 化隆| 宿迁市| 株洲县| 炉霍县| 离岛区| 通辽市| 绥中县| 东海县| 曲水县| 金平| 瓦房店市| 灌南县| 积石山| 布尔津县| 廊坊市| 宁武县| 玉龙| 两当县| 米脂县| 红安县| 光山县| 昌邑市| 云霄县| 遂溪县| 道孚县| 赣榆县| 佛坪县| 瑞昌市| 水富县| 长汀县| 浠水县| 大新县| 五寨县|