UltraMega Blog

10 Common PHP Mistakes to Avoid

These are some very common mistakes that are made in PHP. Some of these can be tricky to catch and can lead to all sorts of strange behavior. So here are 10 common PHP coding mistakes to avoid.

1 '=' Vs. '=='

Using a single '=' in a comparison will cause an assignment and return true, so this mistake can have some pretty unexpected results. It can be hard to catch since it looks perfectly valid to the interpreter if you are comparing something with a variable.

An easy way to avoid this is to swap the subject and variable like this:

if(true = $something) { // Parse error!
   // do stuff

The above will result in a parse error since you can't assign a literal to something, making it easy to catch and fix.

2 '==' Vs. '==='

There is a big difference between the '==' (equal) and '===' (identical) comparison operators. '==' will convert types to match before making the comparison, while '===' will compare directly without converting. So in situations where the difference between '0' and 'false' matters, you must use '==='. Here's some examples:

var_dump(false == 0); // true
var_dump(false === 0); // false
var_dump(false === false); // true
var_dump('0' == 0); // true
var_dump('0' === 0); // false

PHP: Process Array Items With array_map

Let's say you want to run a function on each item in an array. For example, you want to run strip_tags() on all $_POST data. One way to accomplish that is to use a foreach loop and reassign each array element manually, but there's a function for that. The array_map function accepts the name of a function and an array or arrays to run the function on.

So to accomplish our simple example, this is all it takes:

$original = array('<p>Paragraph</p>', '<strong>Bold</strong>');
$new = array_map('strip_tags', $original);
// $new is now array('Paragraph', 'Bold');

You can supply any function, including any you define for more advanced use:

$original = array('<p>Paragraph</p>', '<strong>Bold</strong>');
$new = array_map('clean_input', $original);
function clean_input($value)
    return strip_tags($value, '<p>'); // allow p tags
// $new is now array('<p>Paragraph</p>', 'Bold');

The array_map function is a powerful utility when it comes to working with arrays. You can do things in one line that would otherwise require loops and other complex structures. The examples here are just very basic, but are handy for many everyday tasks. Check the examples in the PHP documentation for other tricks array_map can do.