PHP Pitfalls, common causes of bugs

Crazy E_NOTICE behavior

.
Turns out

$foo = null;
count( $foo['bar'] );

is Valid!

.. Where as..

$foo = array();
count( $foo['bar'] );

Will blow up your application in your face (will trigger E_NOTICE errors ). Which we actually want to happen (if we are good developers). You want to know about these types of problems so you can figure out why the incorrect values were passed. There problem is the NULL you would want to know about more so than the array(), in my opinion.

Special characters in array keys

I had a user who was running a .csv file through a third party program to “fix his new line characters”. For some reason he was having trouble using my CSV import functionality. It turns out this third party program was introducing some kind of non-printable characters that weren’t showing up in any program. Furthermore when I ran print_r() on my array I got output like this:

Array(
  ['foo'] => 'baz',
  ['foo'] => 'bat'

After lost hours and hours I copied and pasted that print_r trace into an email I was composing to someone. The email client showed a special character (in the real example the array indeces differed because one used the letter “s” and the other had some kind of s with a squiggly line over it.)

The moral of this story is non a-zA-Z0-9 can make it into your array indexes.

Include Paths

Lets say you have a folder /app/ and a folder /foo/.

If you created the files:
/app/main.php
/app/include.php
/foo/include.php

and in /app/main.php you wrote:

include( 'include.php' );

Which would you expect to be included? The middle one right? Well if /foo/ is on your include_path think again. For maximum forwards compatibility ALWAYS use absolute paths. Hint: dirname( __FILE__ )

Do you have any more examples of common PHP pitfalls? Post a comment and let me know.

This entry was posted in PHP, Programming. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>