HOWTO · PHP
在 PHP 中使用 == 運算子和 STRCMP 函式進行字串比較
本文展示了 == 運算子和 strcmp 函式如何在 PHP 中比較字串。
等號運算子 == 用於比較變數的值,而相同的運算子 === 用於比較變數與字串值和整數值。
然後,我們將介紹 strcmp() 函式並比較字串。
使用 PHP == 運算子比較 PHP 中的字串
PHP == 運算子,也稱為相等運算子,可以比較變數的值。如果值不同,則運算子返回 false。
在下面的示例中,我們將比較貨幣。
<?php
// Our Currencies
$value1 = "USD";
$value2 = "EUR";
// Use the == to compare our currencies
if ($value1 == $value2) {
echo 'The Currencies are the same';
}
else {
echo 'The Currencies are not the same;
}
?>
輸出:
The Currencies are not the same
上面的比較是正確的,因為 USD 與 EUR 不同。
使用 PHP === 運算子將變數與字串值和整數值進行比較
最好避免使用 == 運算子來比較字串值和整數值的變數。
這就是為什麼;
在下面的示例程式碼中,我們將使用 == 運算子將變數字串值 290 與整數值 290 進行比較。
<?php
// Our variable with an Integer value
$value1 = 290;
// Our variable with a String value
$value2 = "290";
// Compare $value1 with value2 using the == operator
if ($value1 == $value2) {
echo 'The values are the same';
}
else {
echo 'The values are not the same;
}
?>
輸出:
The values are the same
從技術上講,上面的輸出是不正確的,因為資料型別不同。
讓我們看看正確的程式碼。
<?php
// Our variable with an Integer value
$value1 = 290;
// Our variable with a String value
$value2 = "290";
// Compare $value1 with value2 using the === operator
if ($value1 === $value2) {
echo 'The values are the same';
}
else {
echo 'The values are not the same;
}
?>
輸出:
The values are not the same
上述輸出為真,因為我們的值屬於不同的資料型別。
當兩個變數具有相同的資訊和資料型別時,=== 運算子返回 true。
在 PHP 中使用 strcmp() 函式比較字串
strcmp() 函式可以比較字串並顯示第二個字串是否大於、小於或等於第一個字串。
在下面的示例程式碼中,我們將進行比較;
- 員工的名字與同一員工的名字。
- 第一個和第二個名字與名字。
- 第一個名字,第二個和姓氏。
示例程式碼:
<?php
echo strcmp("Joyce","Joyce")."<br>"; // (Equal strings) First name with First name
echo strcmp("Joyce Lynn", "Joyce")."<br>"; // String1 greater than string2
echo strcmp("Joyce", "Joyce Lynn Lee")."<br>"; // String1 less than String 2
?>
輸出:
0
5
-9
當兩個字串相等時,輸出將始終為 =0。
當 String1 大於 String2 時,輸出將是一個隨機值大於 0。
當 String1 小於 String2 時,輸出將是一個隨機值小於<0。