4.7.3 Converting to and from ASCII: chr() and ord()This is NOT the latest copy of this book; click here for the latest version.
string chr ( int ascii)
int ord ( string string)
The American Standard Code for Information Interchange is a special set of 255 numbers that evaluate to letters, symbols, and actions used in most computers. For example, 74 is "J", 106 is "j", 123 is {, and 32 is a space. To convert to ASCII from textual characters, you should use the chr() function, which takes an ASCII value as its only parameter and returns the text equivalent if there is one. The ord() function does the opposite - it takes a string and returns the equivalent ASCII value.
For example:
<?php
$mystr = "ASCII is an easy way for computers to work with strings\n";
if (ord($mystr{1}) == 83) {
print "The second letter in the string is S\n";
} else {
print "The second letter is not S\n";
}
$letter = chr(109);
print "ASCII number 109 is equivalent to $letter\n"; ?>
That should output the following:
The second letter in the string is S
ASCII number 109 is equivalent to m
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|