Common PHP Programming Mistakes

Date: 30 Sep 2009 Comments: 16 so far

1.Using double quotes when you want to output a basic string

echo ‘it\’s ok’;
echo “it’s not”;

When you surround a PHP string in double quotes, it is parsed by the PHP interpreter for variables & special characters, such as “\n”. If you want to output a basic string, use single quotes! it’s a performance benefit, because the since the string does not get parsed.

2. Compare floats for inequality

var_dump(0.1 + 0.2 == 0.3);

it outputs false.

Reason is that it is impossible to express some fractions in decimal notation with a finite number of digits.

3. Calling a method just because method_exists() returned true

Because a method exists does not mean it is callable. if the method is protected or private, method_exists alse returns true even.

4. Using of uninitialized arrays

foreach($items as $item) {
$itemIds[] = $item->getId();
}

Always do

$itemIds = Array();

5. include(“pages/” . $_GET["pg1"]);

The mistake here is the incredible proportions to not check the pg1 variable here.

6. Using mysql_escape_string() instead of mysql_real_escape_string().

7. Unquoted array indexes
echo $array[my_key]; // this is WRONG, but will work

echo $array['my_key']; // this is correct

PHP considers the unquoted index as a “bare” string, and considers it a defined constant. When it can’t find a matching symbol for this constant in the symbol table however, it converts it to a real string, which is why the code above will work.

8. Incorrect using of strpos / stripos

if (strpos(‘devtheweb.net is cool, isn’t it?’, ‘devtheweb.net’)) {
echo “devtheweb.net is cool”;
} else {
echo “devtheweb.net is NOT cool”;
}

This will output “www.devtheweb.net is NOT cool”, as strpos will return 0, which is interpreted as false.

Should be:

if (strpos(‘devtheweb.net is cool, isn’t it?’, ‘devtheweb.net’) !== false) {

OR

if (strpos(‘devtheweb.net is cool, isn’t it?’, ‘devtheweb.net’)>= 0 ) {

  1. 16 Comments to “Common PHP Programming Mistakes”

    1. Kevin says:

      Why is number 4 bad?

    2. [...] more from the original source: Common PHP bProgramming/b Mistakes :Dev-The-Web#39;s Blog SHARETHIS.addEntry({ title: "Common PHP bProgramming/b Mistakes :Dev-The-Web#39;s Blog", url: [...]

    3. Chris says:

      You’ve made a mistake with #1 because you have single quote in your single quoted string which will result in a parse error.

      this:
      echo ‘it’s ok’;
      should be this:
      echo ‘it\’s ok’;

    4. SeanJA says:

      #6 is one of the reasons that I have a problem with php (even though it is my job). They should upgrade their functions rather than polluting the global space with more and more functions that do practically the same thing… *$#%%#*

    5. Rob says:

      Point 1 is a useless over emphasized “tip”, and certainly isn’t a mistake. There’s nothing wrong with using double quotes instead of single-quotes for strings.

      Quoted from Gwynne Raskind in reponse to Google’s web performance website on PHP optimization:
      Benchmarks run against PHP 5.2 and 5.3 show that parsing double-quoted strings with interpolation is no slower (and often faster) than single-quoted strings using concatenation. When simple strings with no variables in them are used, the performance is clearly better with double-quoted strings due to implementation details in the engine. See the benchmark posted at .

      The only time you’d ever notice even the slightest of difference is when quoting strings that are hundreds of megabytes long, in which case, there are probably far more pertinent optimizations you should be looking for.

      In point 2, when making comparison’s always use === to ensure they’re type safe (unless you explicitly require otherwise).

    6. Daniel Platt says:

      number 4 is bad, because everytime a programming has to do error handling, you take a performance hit..

      The other reason is, you are leaving php to decide what the default value is.

      Why is number 6 bad?

    7. Chris says:

      The single quotes argument really only holds up when you’re benchmarking, and at that comparing 0.021 seconds versus 0.024 seconds [made that up but you get my point]…

      I have an entire site which is echoed from “” strings, and that includes *all* html, and it runs super fast. Although, I almost always use single-quote strings for regexs. [I'm rather tired of seeing this posted as a way to improve php performance, which is almost always hindered by mysql or other services [remote or local]].

      Also, great point about #4… if anyone dares to turn on the strict warnings, php will not be a happy camper if you start push()ing an a null var. Plus, if that happens to be in a loop, it resets the var for you :-)

    8. mario says:

      #1 is an idiotic recommendation and has been refuted many times. Double quoted strings are actually faster for common cases and with all recent PHP versions. Btw, the strings are decoded by the tokenizer, not by the parser.

      #6 sounds as if it were written by a WordPress user. String escaping is only used by amateur programmers. If you feel the need for it, you are doing something wrong.
      Go google for “parameterized SQL”. Learn it. Use it.

    9. Keith Casey says:

      Good God, can #1 die yet? Even in benchmarking, you’re talking about microseconds of improvement… so if you’re rendering *thousands* of pages every given second, you *might* see it reach into the millisecond range.

      I’m not sure I see the problem with #4…

      The nasty thing with #5 is not filtering input. Never trust the user. Nope, never.

    10. [...] This post was mentioned on Twitter by Rich and Abdelrahman Omran. Abdelrahman Omran said: Common PHP Programming Mistakes http://bit.ly/3XIBjw [...]

    11. [...] See the article here: Common PHP Programming Mistakes [...]

    12. 1. Performance is not relevant here. Sometimes its just stupid to use ” instead of ‘ and the other way round.
      BTW: WordPress fucked up your quotes :D

      2. That is a real pitfall, only using (int) casting or using intval() saves the day!

      3. Good to know, thanks.

      4. In first place, if foreach gets at least 1 iteration, everything will be ok. Otherwise the array will be NULL which can lead to serious problems.

      5. $_GET, $_POST and $_REQUEST are dangerous. Everybody should be trained to use them correctly!

      6. mysql_real_escape_string is only necesary if you have strings, numbers and floats can be “validated” by simply casting them (int)$number;

      7. A pitfall for beginners. Every devolper should use error_reporting(E_ALL); while developing.

      8. strpos is the functions beginners need to learn that == is not ===.

      Thanks for this list, hope much people will read and use it!

    13. [...] Common PHP Programming Mistakes [...]

    14. shyzwbtk says:

      shyzwbtk…

      shyzwbtk…

    15. admin says:

      Thanks, it’s fixed now :)

    Leave a Reply


    Spam protection by WP Captcha-Free