Converting to and from ASCII

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:

    $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 learn PHP 7?

Hacking with PHP has been fully updated for PHP 7, and is now available as a downloadable PDF. Get over 1200 pages of hands-on PHP learning today!

If this was helpful, please take a moment to tell others about Hacking with PHP by tweeting about it!

Next chapter: Measuring strings >>

Previous chapter: Replacing parts of a string

Jump to:


Home: Table of Contents

Copyright ©2015 Paul Hudson. Follow me: @twostraws.