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:

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

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

print_r($numbers);

Output:

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:

class Person implements Comparable
{
    private...
senior

senior

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

middle

Is there any reason to use strcmp() for strings comparison?

junior

When should I use require vs include ?

middle

What is the difference between PDO's query() vs execute() ?

Bình luận

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

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