PHP - strnatcasecmp() 函式



PHP 的 strnatcasecmp() 函式用於使用自然排序演算法比較兩個字串。“自然排序演算法”指的是一種類似於人類自然排序包含數字的字串的比較方法。

以下是關於返回值的關鍵點列表

  • 如果兩個字串相等,則返回0
  • 如果第一個字串大於第二個字串,則返回1
  • 如果第一個字串小於第二個字串,則返回-1

語法

以下是 PHP strnatcasecmp() 函式的語法:

strnatcasecmp(string $str1, string $str2): int

引數

此函式接受兩個引數,列在下面:

  • str1: 要比較的第一個字串。
  • str2: 與第一個字串進行比較的第二個字串。

返回值

此函式返回一個整數 (即 -1、0、1),基於比較結果。

示例 1

如果兩個字串“相等”,PHP strnatcasecmp() 函式將返回0

<?php
   $str1 = "Tutorialspoint";
   $str2 = "tutorialspoint";
   echo "The given strings are: $str1, and $str2";
   echo "\nAre both the strings equal? ";
   echo strnatcasecmp($str1, $str2);
?>

輸出

上述程式產生以下輸出:

The given strings are: Tutorialspoint, and tutorialspoint
Are both the strings equal? 0

示例 2

如果第一個字串大於第二個字串,PHP strnatcasecmp() 函式將返回1

<?php
   $str1 = "World";
   $str2 = "Hello";
   echo "The given strings are: $str1, and $str2";
   $result = strnatcasecmp($str1, $str2);
   echo "\nThe function returns: $result";
   if($result == 0){
	   echo "\nStrings are equal";
   }
   else if($result == 1){
	   echo "\nFirst string is greater than second one";
   }
   else{
	   echo "\nFirst string is less than the second one";
   }
?>

輸出

執行上述程式後,將顯示以下輸出:

The given strings are: World, and Hello
The function returns: 1
First string is greater than second one

示例 3

如果第一個字串小於第二個字串,PHP strnatcasecmp() 函式將返回-1

<?php
   $str1 = "Java";
   $str2 = "PHP";
   echo "The given strings are: $str1, and $str2";
   $result = strnatcasecmp($str1, $str2);
   echo "\nThe function returns: $result";
   if($result == 0){
	   echo "\nStrings are equal";
   }
   else if($result == 1){
	   echo "\nFirst string is greater than second one";
   }
   else{
	   echo "\nFirst string is less than the second one";
   }
?>

輸出

以下是上述程式的輸出:

The given strings are: Java, and PHP
The function returns: -1
First string is less than the second one
php_function_reference.htm
廣告