Pete
Pete

Reputation: 1305

php's range function behavior

PHP.net's documentation 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.

Upvotes: 2

Views: 283

Answers (3)

user229044
user229044

Reputation: 239432

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.

Upvotes: 4

FatherStorm
FatherStorm

Reputation: 7183

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.

Upvotes: 0

Matthew
Matthew

Reputation: 48304

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.

Upvotes: 0

Related Questions