Câu hỏi phỏng vấn PHP
Câu hỏi

What is use of Sp...

Câu trả lời

The spaceship operator, also known as the combined comparison operator, is a PHP operator introduced in PHP 7.0. It is denoted by the symbol <=> and is used for comparing two expressions. The spaceship operator returns:

  • 1 if the left operand is greater than the right operand
  • 0 if the left operand is equal to the right operand
  • -1 if the left operand is less than the right operand

Here are some common use cases for the spaceship operator:

Sorting Arrays

The spaceship operator is commonly used in combination with the usort() or uasort() functions to sort arrays based on a custom comparison function. For example:

php Copy
$numbers = [5, 2, 8, 1, 9];

usort($numbers, function($a, $b) {
    return $a <=> $b;
});

print_r($numbers);

Output:

Copy
Array
(
    [0] => 1
    [1] => 2
    [2] => 5
    [3] => 8
    [4] => 9
)

Implementing Interfaces

When implementing interfaces that require comparison methods, such as Comparable or Countable, the spaceship operator can be used to provide a concise implementation. For example:

php Copy
class Person implements Comparable
{
    private...
senior

senior

Gợi ý câu hỏi phỏng vấn

junior

Is multiple inheritance supported in PHP?

junior

What are the main differences between const vs define

senior

How to turn errors into exceptions in PHP?

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào