How would you like to be able to record hundreds, or thousands of different yes/no values in a single number? This is just one of the many applications where base_convert can come in handy.
Remember basic math classes in high school, where you learned about binary numbers, and hexadecimal, and other number systems that use a different base than our standard base 10? Remember reading about computers, and how they are ultimately just binary number crunchers? Well let’s put that fund of knowledge to work in our PHP programs.
Suppose you have an on-line questionnaire, with hundreds of questions to which people can reply with a simple yes/no response. You need to record the tens of thousands of results for later analysis. You can do it with a simple integer. In fact, if you have fewer than 64,000 questions (and let’s hope for your subject’s sake that there aren’t that many!) you can use a small integer (SMALLINT) in your mysql database.
How? Well, simply convert each answer into zeros and ones, to create a binary number. Let’s say for example the first five questions were answered ‘yes’ and the next five ‘no’ by a particular subject. You save that as 1111100000. Now use base_convert(1111100000,2,10) and PHP converts the base two number into base 10 for easy storage in your database. Retrieve the number from the database, and convert it back into base two using base_convert(#,10,2). Simple and quick, it saves tons of storage space.
Substitute Using str_replace
Sometimes you simply want to replace part of string with something else, like changing your address when you move. You could use a fancy grep replace or similar functionality, but if it is a simple substitution it is usually easier to just go with the string function str_replace.
Here is how it works:
$newwork = str_replace($old, $new, $work)
Just set $old to the string of characters you want replaced, $new to the new value you want there (it can be an empty string if you just want to remove something without replacing it), and $work is your original string text. The modified version will be stored in $newwork.
Get the Current Directory
Sometimes you write a function in PHP that needs to know where in the directory hierarchy the code is being called from, to correctly access other files, such as those to be read, written or included. If the same function appears throughout your site, you can’t ‘hard code’ the location, because it changes from one web page to another, if you site spans more than one directory.
PHP, of course, provides a simple solution:
$dir=getcwd();
So, for example, using the above code in a script on your page at mysite.com/widgets/goodstuff.php might return the value:
home/mysite/public_html/widgets
The only cautionary note when using this function, is to remember that it will return the working directory of the calling script, rather than included script, if it is used within an include. So, if your
$dir=getcwd();
is in a file at home/mysite/public_html/includes
And you include it in a script running at home/mysite/public_html/widgets
It will set the $dir variable to that second path, not the path where the included file resides.
Make a Choice with SWITCH()
The switch() function lets you choose between several options, depending on the value some variable takes. It is similar, for those of you who have programmed in Visual Basic, to the select case command in that language.
So, let’s say you have a feedback form with a drop-down list of typical reasons someone might have for contacting your company. They have to categorize their message as
- request for information
- order not received
- order arrived damaged
- other
The form is programmed to assign the number next to each of those reasons to a variable $reason. Depending on the type of message, you want to route the form to different departments:
switch($reason)
{
case 1: $destination=”fred@thiscompany.com”; break;
case 2: $destination=”mary@thiscompany.com”;break;
case 3: $destination=”arnold@thiscompany.com”;break;
default: $destination=”bob@thiscompany.com”;
}
Notice we didn’t assign #4 to the last option, but used ‘default’ a catch-all that is executed if none of the other values match. This way, bob will get any messages that do not have the $reason variable set. Also note that each option except the last needs a ‘break’ command at the end, to ensure that subsequent options are not considered. In this case, the default option would execute every time if you forgot the breaks.
Remove Duplicates from an Array
Sometimes you have an array of elements that may contain duplicate entries, but you do want any duplication. Randomly selected elements are a good example of this. If you add elements to an array one at a time using the random function, it can return the same value more than once.
Removing any duplicates is easy … just use array_unique().
$newarray=array_unique($oldarray);
Any time to identical entries are identified, the second one will be removed from the array. Remember that this may leave you with an array having missing index values. That is no worry if you are going through the array using the foreach() function, but if you want to use for($x=0;$x<12;++$x) you will have problems.
You can fix that by reordering your array keys using array_values():
$correctarray=array_values($newarray);
This will take the $newarray created in the earlier line, and replace the key values with new ones, starting at zero and proceeding sequentially.