PHP Errors – 10 Common Mistakes

Everyone makes mistakes when writing PHP code no matter your experience level. There are many common mistakes that sometimes are not immediately clear when looking at the error that PHP displays. First and foremost, when debugging PHP code, make sure you include the proper code to Display PHP Errors.
Each item will be organized by the PHP error itself, followed by chunks of invalid code that will be used as the baseline for the common mistakes, and finally the corrected code and solution will be presented.

  1. Parse error: syntax error, unexpected ‘}’ … on line 62

  2. 48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    
    foreach ($assoc_array as $key=>$value)
    	echo "$key contains $value\n\r";
     
    	switch ($key){
    		case 'name':
    			echo 'Name found!';
    			break;
    		case 'age':			
    			echo 'Age found!';
    			break;
    		default:
    			echo 'No Case found!';
    			break;
    	}
    }

    When you forget an opening curly brace ‘{‘, or if you have an extra closing curly brace, this error is generated at the closing brace, referred to in the above example as line 62. Many frameworks and syntax highlighters such as Notepad++ will assist you in finding the matching brace by simply placing your cursor next to a curly brace.

    Answer: Add the opening brace to the end of line 48:

    48
    
    foreach ($assoc_array as $key=>$value){
  3. Parse error: syntax error, unexpected $end … on line 63

  4. 48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    
    foreach ($assoc_array as $key=>$value){
    	echo "$key contains $value\n\r";
     
    	switch ($key){
    		case 'name':
    			echo 'Name found!';
    			break;
    		case 'age':			
    			echo 'Age found!';
    			break;
    		default:
    			echo 'No Case found!';
    			break;
     
    }

    On the opposite end of the spectrum, forgetting a closing curly brace ‘}’ will generate this obscure error. Obscure because the line number refers to the bottom of the page. It is unable to identify the closing of the control structure.

    Answer: Add the closing brace for the switch that begins on line 51. In the sample code, the brace is missing from line 61:

    58
    59
    60
    61
    62
    
    		default:
    			echo 'No Case found!';
    			break;
    	}
    }
  5. Parse error: syntax error, unexpected ‘{‘ … on line 42

  6. 42
    43
    44
    45
    46
    
    if ($numeric == 1 { 
    	echo 'Equal to 1'; 
      }else{
    	echo 'Not equal to 1';
    }

    While this may seem obvious with the simplified example above, this comes up very often when you have functions nested inside of the evaluated expression of a control structure. For a momentary detour, here is an example of the exact situation that could easily lead to this error. Note: This sample code would also generate the same error.

    if ($numeric == stripslashes(intval(1)){ 
    	echo 'Equal to 1'; 
      }else{
    	echo 'Not equal to 1';
    }

    The error is generated because of a missing closing parenthesis ‘)’. In the above cases, the missing character is the matched pair to the opening parenthesis ‘(‘ that encompasses the evaluated expression. In the very first line, you can count 3 ‘(‘ and only 2 ‘)’, causing PHP to reach an unexpected curly brace which begins the behaviour when the expression is evaluated as TRUE.

    Answer: Add the closing parenthesis to line 42.

    42
    
    if ($numeric == 1) {
  7. Parse error: syntax error, unexpected T_VARIABLE … on line 38

  8. 37
    38
    39
    
    $num_array[] = 5
    $get_test = $_GET['test'];
    $escaped = 'A great movie is \'Shawshank Redemption\', in my humble opinion.';

    The error has identified the variable $get_test on line 38 and is surprised by its presence suddenly! Why? Because the most important character in all PHP programming is missing, and as soon as it reaches the next item, it throws out the error, the specific error because the next item is a variable. It is reading the line as if it was written:

    $num_array[] = 5$get_test = $_GET['test'];

    Answer: There is a semicolon missing after the 5 on line 37, closing the behaviour of assigning the integer 5 to the next numeric index in the $num_array array variable.

    37
    
    $num_array[] = 5;
  9. Parse error: syntax error, unexpected ‘}’, expecting ‘,’ or ‘;’ … on line 44

  10. 42
    43
    44
    45
    46
    
    if ($numeric == 1){ 
    	echo 'Equal to 1'
      }else{
    	echo 'Not equal to 1';
    }

    Ok, this is the same problem as the previous item in the list, but the error is completely different because of the next element reached by PHP after the missing character. In the above example, PHP identifies the opening curly brace of the else statement.

    Answer: There is a semicolon missing after the echo statement on line 43, leading PHP to unexpectedly reach the closing brace of the if statement.

    42
    43
    44
    
    if ($numeric == 1){ 
    	echo 'Equal to 1';
      }else{
  11. Parse error: syntax error, unexpected ‘,’ … on line 38

  12. 38
    
    $escaped = 'A great movie is \'Shawshank Redemption', in my humble opinion.';

    Using a syntax highlighter should make this error very evident, as you notice that the string that is being assigned to the variable $escaped changes its coloring midway through. The entire string is surrounded by single quotes, however single quotes are also used inside, and while the first one has been escaped by a backslash so it is evaluated as a single quote character rather than the encapsulating single quotes, it seems that one is missing…

    Answer: Escape the 3rd single quote, after Redemption, which in the above example is acting as the closing single quote to identify the string.

    38
    
    $escaped = 'A great movie is \'Shawshank Redemption\', in my humble opinion.';
  13. Parse error: syntax error, unexpected ‘=’, expecting ‘)’ … on line 32

  14. 32
    33
    
    $assoc_array = array('name' = 'John Smith', 'age' => 35, 'gender' => 'male');
    $num_array = array(1,2,'three','four');

    When defining an array, you can refer to simply the values (and let the index be assigned numerically and automatically) or you can define the key and value pairs. Any other syntax can trigger a parsing error, since PHP is expecting that before placing an equals sign you would close the array.

    Answer: Line 32 is missing the greater than symbol after the equals sign to define the value for the key ‘name’.

    32
    
    $assoc_array = array('name' => 'John Smith', 'age' => 35, 'gender' => 'male');
  15. Parse error: syntax error, unexpected T_STRING, expecting ‘)’ … on line 32

  16. 32
    33
    
    $assoc_array = array('name' = John Smith, 'age' => 35, 'gender' => 'male');
    $num_array = array(1,2,'three','four');

    Variable types have specific syntax when assigning the values. Arrays use array(), integers and floats are written directly sans extraneous syntax (e.g. $variable = 12; ), and strings are surrounded by single or double quotes. Neglecting to surround a string with quotations causes PHP to find an unexpected T_STRING and look for a missing character that is part of a control structure or language construct.

    Answer: John Smith is a string, the value of the key ‘name’ (also a string), but was missing quotation marks.

    32
    
    $assoc_array = array('name' => 'John Smith', 'age' => 35, 'gender' => 'male');
  17. Warning: Missing argument 1 for preprint(), called … on line 27 and defined … on line 21

  18. 21
    22
    23
    24
    25
    26
    27
    
    function preprint($parray) {
    	$nl = "\n\r";
    	echo '
    ' . $nl;
    	print_r($parray);
    }
    $assoc_array = array('name' => 'John Smith', 'age' => 35, 'gender' => 'male');
    preprint();

    The error states that a function, called on line 27, is missing the first argument (e.g. the elements within the parenthesis), as defined by the function that is created on line 21. When the function is written to expect an argument, and none is provided nor the argument within the function has a default value assigned, a PHP warning is presented. If the function was written as follows, with a default value, the warning would not appear and the default value would be used:

    function preprint($parray = array('name' => 'Test')) {
    	$nl = "\n\r";
    	echo '
    ' . $nl;
    	print_r($parray);
    }

    Answer: Provide the argument in the function call on line 27.

    26
    27
    
    $assoc_array = array('name' => 'John Smith', 'age' => 35, 'gender' => 'male');
    preprint($assoc_array);
  19. Make sure you understand the difference between == and ===

  20. Ok, so this last one isn’t a PHP error, but it bears repeating. Failing to understand the difference and the appropriate usage of equality and identical comparison operators will not generate an error by PHP, but will likely find you debugging your code for a very long time, wondering what is wrong with your data. Make sure you understand the equals sign in PHP! Remember, the following If statement will always be TRUE because you are assigning the variable rather than evaluating it:

    if ($numeric = 1){ 
    	echo 'Equal to 1';
      }else{
    	echo 'Not equal to 1';
    }

PHP can be a cruel mistress, but if you decode the PHP errors and warnings, you’ll find the total time building your application, website, or school project will be dramatically reduced!

Seven Downloads for Young Web Developers

There are tons of books and tutorials on PHP, MySQL, Zend, and SEO on store shelves. There are even more resources found only on the internet. Sometimes you need something in the middle, content you can download legally and keep handy when you are offline. Below are a few completely free resources that most beginner or intermediate web developers (even if you do it just for yourself) will find useful.

PHP

1) PHP Reference: Beginner to Intermediate PHP5

Shameless self-promotion. A reference for many of the functions within PHP that serves as a quick go-to resource for checking syntax and remembering the nuances of many of the functions. It is available as a PHP book you can purchase in print, however the entire book is released under creative commons and available as a PHP reference PDF.

2) Object Oriented PHP Tutorial in PDF

Provided by killerphp.com and Stefan Mischook, this is a PDF version of his article on the topic of object orientated programming in PHP. It gives a conversational explanation to the basics. More information and the OOP PHP PDF is available over on killerphp.com.

3) Zend Framework: Surviving the Deep End

The Zend Framework can help developers organize and write more efficient PHP code for large projects and has become one of the top frameworks used online today. From the page…

“The book was written to guide readers through the metaphorical ‘Deep End’. It’s the place you find yourself in when you complete a few tutorials and scan through the Reference Guide, where you are buried in knowledge up to your neck but without a clue about how to bind it all together effectively into an application.”

While available online, there is a link to downloading the PDF version in the bottom right. Check out the Zend Framework survival guide.

HTML, CSS, AJAX

4) The Woork Handbook

Another compilation of online articles compiled and organized as an offline document. From the page…

“The Woork Handbook is a free eBook about CSS, HTML, Ajax, web programming, Mootools, Scriptaculous and other topics about web design… directly from Woork!”

This isn’t a full study of any single topic, but is filled with tidbits. Grab the Woork Handbook.

5) Added Bytes Cheat Sheets (formerly ILoveJackDaniels)

While the site’s name has changed, the great resources have not. Cheat sheets are designed to cram (in a useful way) tons of information into the front and back of an 8.5″ x 11″ sheet of paper. There is little excuse for not keeping these handy. Grab the cheat sheets for HTML, CSS, RegEx, Mod_Rewrite, and more.

MySQL

6) MySQL Manual

All MySQL documentation is available as a downloadable file. Choose from various options for the MySQL documentation.
Editor’s Note: I had trouble finding a good, free, legal resource for MySQL that wasn’t hyper specific and was user friendly. I hope others have suggestions they can leave in the comments.

SEO (Search Engine Optimization)

7) Beginner’s Guide to Search Engine Optimization

SEOMoz.org is an amazing website for learning the complex world of SEO with a very clear, user-friendly tone. Besides that, they offer a bunch of tools for helping your new website get better in the eyes of search engines (aka Google). Available as HTML, MS Word, or an OpenOffice document, you can get a copy of the Beginner’s Guide to Search Engine Optimization over on SEOMoz.org.