gbalduzzi
gbalduzzi

Reputation: 10176

How can i check if a character is in a range of characters?

I have a character and i need to check if it is in a given range, i.e. between 'A' and 'F'.

Of course i could do

if ($c == 'A' || $c == 'B' || ..)

but it is terrible.

Any suggestions?

Upvotes: 2

Views: 1847

Answers (2)

Will
Will

Reputation: 24699

You can use ord() to get the ordinal ASCII character code:

if (ord($c) >= ord('A') && ord($c) <= ord('F')) {
    echo "Character is in range."
}

Note that this is only "uppercase A through uppercase F". For case-insensitive, use strtoupper($c) where you see $c.

Upvotes: 5

Sherif
Sherif

Reputation: 11943

You could convert the character to its ordinal value and check its integer range. Such as if (ord($c) >= ord('A') && ord($c) <= ord('F'))

Upvotes: 1

Related Questions