|
With all the initialization complete, the next step in the script is to cycle through each individual character within the message to encode using a for() loop starting from 0 to the length returned by the strlen() function. The strlen() function returns the length of the provided string (strings are discussed in detail in ). Because a number of cryptogram-generated characters don't translate (punctuation, whitespace, and so on) it is necessary to check to see that each character in the message being encoded exists prior to attempting to encode it. To do so, use the in_array() function to ensure that the character exists within the $cryptogram lookup table. If there is no translation available for the particular character (meaning in_array() returned false) it is passed straight into the encoded message stored in the $encoded variable. Otherwise, the character is translated based on the $cryptogram array. However, because the $cryptogram array's keys are not characters (recall that they are integer values 025) the $alphabet array is used to retrieve the particular integer value for the given character.
After the message is processed character-by-character, $encoded contains the complete cryptogram for the message (which is then displayed to the client). Because this script generates a completely new cryptogram every time it is executed, it is impossible to display the exact output. However, when this script was executed, my output was the following:
DPYM YM RJ MHAXB MXUBXD RXMMOEX!
Converting from Strings to Arrays and Back
As introduced in , you can use a number of methods for processing strings in PHP. One very common use of arrays is processing a list of items represented as a string, such as the following:
John Coggeshall, Max Smith, Mary Johnston
When processing such a list, PHP provides a function that allows you to tokenize (separate) string values by a constant separatorthe explode() function with the following syntax:
explode($separator, $string [, $limit]);
$separator is the string that will represent the separator that $string will be broken into. Optionally, you can also pass the $limit parameter, which represents the maximum number of splits to occur. When executed, the explode() function breaks a string into individual array elements using the value of $separator to indicate where each split will occur. Using our earlier string list, to break apart each name the comma character (,) would be used as shown in
Tags:
Add more tags...,
|