AlexMorley-Finch
AlexMorley-Finch

Reputation: 6955

PHP, uppercase a single character

Essentially, what I want to know is, will this:

echo chr(ord('a')-32);

Work for every a-z letter, on every possible PHP installation, every single time?

Read here for a bit of background information

After searching for a while, I realised that most of the questions for changing string case in PHP only apply to entire words or sentences.

I have a case where I only need to upper 1 single character.

I though using functions like strtoupper, ucfirst and ucwords were overkill for single characters, seeing as they are designed to work with strings.

So after looking around php.net I found the functions chr and ord which convert chars to their ascii representation (and back).

After a little playing, I discovered I can convert a lower to an upper by doing

echo chr(ord('a')-32);

This simply offsets the character by 32 places in the ascii table. Which just happens to be the character's upper version.

The reason I'm posting this on stackoverflow, is because I want to know if there are any edge cases that could break this simple conversion.

Would changing the character set of the php script, or somethig like that affect the outcome?

Is this $upper = chr(ord($lower)-$offset) the standard way to upper a char in PHP? or is there another?

Upvotes: 0

Views: 2096

Answers (1)

ohaal
ohaal

Reputation: 5268

The ASCII code doesn't change between PHP installations, because it is based on the ASCII table.

Quote from www.asciitable.com:

ASCII stands for American Standard Code for Information Interchange. Computers can only understand numbers, so an ASCII code is the numerical representation of a character such as 'a' or '@' or an action of some sort. ASCII was developed a long time ago and now the non-printing characters are rarely used for their original purpose.

Quote from PHP documentation on chr():

Returns a one-character string containing the character specified by ascii.

In any case, I'd say it's more overkill to do it your way than do it with strtoupper().

strtoupper() is also faster.

Upvotes: 3

Related Questions