开发者

php's range function behavior

PHP.net's documentat开发者_如何转开发ion on the range function is a little lacking. These functions produce unexpected (to me anyways) results when given character ranges.

$m = range('A','z'); print_r($m); $m = range('~','"'); print_r($m);

I'm looking for a reference that might explicitly define its behavior.


The issue is that range treats its arguments like integers, and if you give it a single character it will convert it to its ASCII character code.

In the first case, you're getting all characters between character 'A' (integer 65) and character 'z' (integer 122). This is expected behavior for those of us coming from a C (or C-like language) background.

This is one of the rare cases where PHP converts single characters to their ASCII codes rather than parsing the string as integer the way it does normally. Most of the PHP documentation is better at telling you when to expect this. strpos for example, notes:

Needle

If needle is not a string, it is converted to an integer and applied as the ordinal value of a character.

The documentation for range is strangely quiet about it.


Consider:

foreach (range('A','z') as $c)
  echo $c."\n";

to be equivalent to:

for ($i = ord('A'); $i <= ord('z'); ++$i)
  echo chr($i)."\n";

Likewise, your second example is equivalent to (since ord('~') > ord('"')):

for ($i = ord('~'); $i >= ord('"'); --$i)
  echo chr($i)."\n";

It's not well documented, but that's how it is supposed to work.


that is because " is a lower character than ~ try

m = range('A','z'); print_r($m);

$m = range('z','A'); print_r($m);

the characters are pulled by their chr (ASCII Table) values:

http://www.asciitable.com/

the array is returned in the directional order of the 2 parameters.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜