1

I am writing a sort function (using usort), and part of the operation I want to do there is determining which value comes first alphabetically. (This is only part of the operation, hence I'm not using natsort.) This means I have two strings for which I need to determine which is alphabetically first. Since this operation gets done in a loop, I want to have this done as simple as possible. One thing I could do is construct an array out of the two elements and use natsort on that. Is there a better approach, that does not involve constructing an array from the two values?

Edit: $a > $b seems to get basic cases right, though I'm not sure of how correct this behaves.

4

1 回答 1

2

用于strcmp

从文档中:

如果 str1 小于 str2,则返回 < 0;> 0 如果 str1 大于 str2,如果它们相等则为 0。

代码:

$str1 = 'foo';
$str2 = 'bar';

if(strcmp($str1, $str2) < 0) {
  echo '$str1 comes first';
} elseif(strcmp($str1, $str2) > 0 ){
  echo '$str2 comes first';
} 

输出:

$str2 comes first

演示!

于 2013-09-22T20:34:21.997 回答