PHP like many other programming languages has facilities to handle exceptions. Using them is pretty easy, but sometimes lazy programmers seems to misuse them to suppress error messages. A try/catch in PHP is usually constructed something like this:
try { // Something can go (horribly) wrong... } catch { } The lazy programmer may leave the catch empty, but frankly you should never do it. When you’re doing something - try’ing - it’s for a reason, and if it fails, someone quite possible need to know - the end user, a log file for the sysadm or someone else.
In PHP when you have a string and want to find out if it contains another string, there are a few ways to do it. You can use regular expressions, use the strstr functions and a few other methods. The easiest way though is probably by using strpos, which returns the number of the character containing the first occurrence of the thing you’re looking for - and false if the string isn’t found.
When using memcache from PHP, you can save values with either set or replace. You can probably safely ignore the replace method:
“Memcached::replace() is similar to Memcached::set(), but the operation fails if the key does not exist on the server.”
- PHP Documentation
In PHP many things can be done several different ways. Picking which way to do something may be a matter of personal taste or habit. Sometimes however, things may be much clearer for the next developer, if you choose one way over another.
A very simple example of this, is adding a new item to an array. Often I come across this construct: $valuepairs[] = 'Some value'
It’s valid and compact syntax, but in terms of clarity, I’d prefer this construct anytime:
A url may contain a hash/an anchor reference. If you need to remove it from url, it’s quite easy. Here’s a short recipe on how to do it in PHP (including a little test input):
$urls = array( 'http://example.com/', 'http://example.com/#test', 'http://example.com/?id=1', 'http://example.com/?id=1#test', 'http://example.com/?id=1&id2=2#test#test', 'http://example.com/?id=1#test#test' ); foreach ($urls as $url) { if (strpos($url, '#')) { $url = substr($url, 0, strpos($url, '#')); } echo $url, "\\n"; } Apart from removing the hash ending from urls, the function can naturally also be used on any number of other similar cases, where you need to trim a string.