PHP如何用比较运算符比较字符串?

2022-01-25 00:00:00 string operators compare php type-coercion

我正在用比较运算符比较字符串.

I'm comparing strings with comparison operators.

对于以下两个比较及其结果,我需要一些简短的解释.

I needs some short of explanations for the below two comparisons and their result.

if('ai' > 'i')
{
    echo 'Yes';
}
else
{
    echo 'No';
}

output: No

为什么这些输出是这样的?

Why do these output this way?

if('ia' > 'i')
{
    echo 'Yes';
}
else
{
    echo 'No';
}

Output: Yes

再说一遍,为什么?

也许我忘记了一些基础知识,但我确实需要对这些比较示例进行一些解释才能理解此输出.

Maybe I forgot some basics, but I really need some explanation of these comparison examples to understand this output.

推荐答案

PHP 将根据字母顺序使用大于和小于比较运算符比较 alpha 字符串.

PHP will compare alpha strings using the greater than and less than comparison operators based upon alphabetical order.

  • 在第一个示例中,ai 按字母顺序排在 i 之前,因此 >(大于)的测试是false - 前面的顺序被认为是小于"而不是大于".

  • In the first example, ai comes before i in alphabetical order so the test of > (greater than) is false - earlier in the order is considered 'less than' rather than 'greater than'.

在第二个例子中,ia 出现在 i 字母顺序之后,所以 > 的测试(大于)是 true - 按大于"的顺序排列.

In the second example, ia comes after i alphabetical order so the test of > (greater than) is true - later in the order being considered 'greater than'.

相关文章