| Implementing Arrays |
| Article Index |
|---|
| Implementing Arrays |
| Page 2 |
| Page 3 |
| Page 4 |
| Page 5 |
| Page 6 |
| Page 7 |
| Page 8 |
| Page 9 |
| Page 10 |
array_flip($input)
$input represents the array to flip, and when executed, array_flip() returns the new (flipped) array.
Finally, take a look at your first search function in PHPthe in_array() function. This function takes two parameters (the value being searched for and the array to search) and returns a Boolean value indicating whether the particular value was found as described in the syntax that follows:
in_array($needle, $haystack [, $strict])
Note that the in_array() function also provides a third optional parameter, $strict. This optional Boolean value (false by default) determines whether the value specified in the $needle parameter must match not only the value, but the data type found in the corresponding array, $haystack. Thus, in an array with the string value 10, searching for the integer value 10 would return true. However, by setting the $strict parameter to true the same operation would return false.
Now that you have been introduced to the new functions being used in this example, let's take a look at the first portion of the cryptogram script, as shown in :
NOTEIn , the closing PHP tag ?> is intentionally omitted because it is only a fragment of the script. |
Listing 2.17. A Cryptogram Generator Using PHP Arrays (Part 1)
<?php
/* Initialize the random number generator */
srand((double)microtime() * 1000000);
$message = "This is my super secret message!";
$message = strtoupper($message);
/* Create an alphabet array whose keys are the letters A-Z, and whose
values are the numbers 0 - 25 respectively */
$alphabet = array_flip(range('A', 'Z'));
$cryptogram = range('A', 'Z');
/* Randomize the lookup table used for the cryptogram generation */
shuffle($cryptogram);
As shown in , the first step in your cryptogram script is the initialization of the random-number generator. As was the case with array_rand(), the shuffle() function requires this to function properly. The $message variable (which represents the actual string you are encoding) is then initialized and converted to uppercase using the strtoupper() function. Using a combination of the range() function coupled with the array_flip() function, we create an associative array, $alphabet, which has key values for every letter in the alphabet and associates these values with the integers 0 tHRough 25. Complementing the $alphabet variable is the $cryptogram variable, which is initialized with 26 values representing the letters of the alphabet. The $cryptogram variable will be used to encode the message into the final cryptogram.
| Users' Comments (0) |
|
No comment posted








