How to use the spaceship operator in PHP7
Editor to share with you how to use the spaceship operator in PHP7, I believe most people do not know much about it, so share this article for your reference, I hope you can learn a lot after reading this article, let's learn about it!
Spaceship operator
It is written like this. It combines comparison. It means "less than, equal to, or greater than". It is useful when sorting arrays using a user-defined price comparison function because the return value is:
0 if the value is equal
1 if the value on the left is larger
-1 if the value on the right is larger
So, let's sort the following actresses:
ActressesWithAcademyAwards = [['name' = >' Katharine Hepburn', 'awards' = > 4], [' name' = > 'Jessica Lange',' awards' = > 2], ['name' = >' Meryl Streep', 'awards' = > 3], [' name' = > 'Cate Blanchett',' awards' = > 2],]
You can compare one line instead of multiple lines:
Usort ($actressesWithAcademyAwards, function ($a, $b) {return $a ['awards'] $b [' awards'];}); print_r ($actressesWithAcademyAwards)
Return:
Array
(
[0] = > Array
(
[name] = > Jessica Lange
[awards] = > 2
)
[1] = > Array
(
[name] = > Cate Blanchett
[awards] = > 2
)
[2] = > Array
(
[name] = > Meryl Streep
[awards] = > 3
)
[3] = > Array
(
[name] = > Katharine Hepburn
[awards] = > 4
)
)
This is a very common PHP use case, so the spaceship operator can save time. In addition, it is more readable.
These are all the contents of the article "how to use spacecraft operators in PHP7". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!