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:

<?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

 

Next chapter: Measuring strings >>

Previous chapter: Replacing parts of a string

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar