Here are some PHP observations that I have been caught out with and am posting so I don't get caught again. This post will grow over time as I find more bite-size nuggets.
Gotcha: Array Merge
Guess what the output to this code will be:
<?php $lookup_table = array(); $lookup_table['hello'] = array(); $lookup_table['hello'] = 1; $lookup_table['hello'] = 2; $my_array1 = array(); $my_array1 = array_merge($my_array1, $lookup_table['hello']); $my_array1 = array_merge($my_array1, $lookup_table['world']); $my_array1 = array_merge($my_array1, $lookup_table['hello']); print_r($my_array1);
The answer is nothing. Not only does the script not throw an error, but the merged array loses all elements that it was holding at the point of passing a null value as a parameter, as well as all future elements that would be merged after that call. If you manually run the script, you may see some notices and warnings, but you probably won't see these if the script is called by another script, or if your php ini settings are set to not shown warnings/notices (production settings).
I write interactive PHP scripts all the time for CLI tools. This often requires getting a variable from the user using readline. An example piece of code would be:
$search_string = readline('Enter the string of text you wish to replace: ' . PHP_EOL);
PHP_EOL at the end is so that the user inputs the answer on a new line but this doesn't work! Instead you need to do this:
print 'Enter the string of text you wish to replace: ' . PHP_EOL; $search_string = readline();
At one point, I was using
empty() to "quickly" check if an array hadn't been given any values. This is because I didn't know at the time that the
count() function is actually O(1) and not O(n) like I had assumed (i.e. it doesn't actually loop through the elements and count them). Thus you can use them interchangeably.
is_int() will not evaluate true for a value of
is_numeric would. Remember that all
$_POST values, as well as values retrieved from MySql are actually in string form unless you, or your libraries, have done this for you.
As a rule of thumb, use single quotes (
') on the patterns for regular expresssions. This will save you headaches when you use the
$ symbol for specifying the end of the pattern as shown below.
$pattern = "|^[0-9]*$|"
$ symbol within double quotes tries to evaluate a variable.
Don't forget that you need to specify a character for the start and end of your regular expression pattern when passing to
preg_match etc. In the example before, I used the
| character but other examples on the net use other characters.