1.4 Converting ASII Codes into Characters


1.4 Converting ASII Codes into Characters

You want to convert ASCII codes into English or vice versa.

Technique

Use chr() and ord() or sprintf() to convert back and forth:

 <?php $letter = chr (67); // Upper case C $ascii_code = ord ($letter); // 67 $letter = sprintf ("%c", $ascii_code); // Upper case C ?> 

Comments

On the surface, converting ASCII values seems to be a pretty useless task. When I was a beginning programmer (Perl at the time), I thought that it was pointless for people even to write these functions and explanations . However, there are many cases in which you do need to convert back and forth. For example, let's say that you have binary data stored in an ODBC database, and you want to extract it as a string, but (gasp) it is returned in ASCII codes instead of characters! If this happens, the chr() and ord() functions suddenly become incredibly useful. You can also try the unpack() function to help with the conversion.

The chr() function takes one ASCII code and converts it to a character. The ord() function does the same thing in reverse; it takes a character and converts it to an ASCII code. For the code to convert an ASCII string, look at recipe 1.5.



PHP Developer's Cookbook
PHP Developers Cookbook (2nd Edition)
ISBN: 0672323257
EAN: 2147483647
Year: 2000
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net