Experiment with Basic PHP Syntax Errors

When you start PHP, you will see errors. They stop your program, and sometimes a small mistake takes a long time to find. A good way to get friendly with them is to make the mistakes yourself and see the message. Then you will know them when they come in real work.


A working program

<?php
echo "Hello World!";
?>

Output:

Tutorials Class - Output Window

Hello World!

Now we will break this program in different ways. Run each example on your local computer and read the message. The file name and line number in your messages will be different.


Experiment 1: missing semicolon

<?php
echo "Hello"
echo " World";
?>
Tutorials Class - Output Window

Parse error: syntax error, unexpected token “echo”, expecting “,” or “;” in /path/index.php on line 3

PHP reports the line after the missing semicolon, because it only understands the problem when it reads the next statement.

Experiment 2: undefined variable

<?php
$name = "Robin";
echo $nme;     // typing mistake
?>
Tutorials Class - Output Window

Warning: Undefined variable $nme in /path/index.php on line 3

This is only a warning, so the script goes on. The cause is a typing mistake, or the different case of the variable name.

Experiment 3: unknown function

<?php
printt("Hello");
?>
Tutorials Class - Output Window

Fatal error: Uncaught Error: Call to undefined function printt()

Experiment 4: bracket not closed

<?php
if (true) {
    echo "Yes";
?>
Tutorials Class - Output Window

Parse error: Unclosed ‘{‘ on line 2

Experiment 5: divide by zero

<?php
echo 10 / 0;
?>
Tutorials Class - Output Window

Fatal error: Uncaught DivisionByZeroError: Division by zero


What to learn from it

  • Parse errors are syntax mistakes. The program does not start at all.
  • Warnings and notices do not stop the program, but they show a problem to fix.
  • Fatal errors stop the program in the middle.

See all types of errors in PHP Errors and the types of errors in PHP.


Learn more about the similar topics:
Tutorials
PHP Introduction
PHP Terminology
PHP Installation
PHP Syntax
PHP Comments
PHP exit() Function
Exercises & Assignments
Write a program to print “Hello World” using echo
Simple Tips for PHP Beginners
Experiment with Basic PHP Syntax Errors
Using phpinfo() – Display PHP Configuration & Modules
Interview Questions & Answers
What is PHP?
Who is the father of PHP?
What is the correct & common way to start and finish a PHP block of code?
What is Open Source Software?
What is the default extension of the PHP file?
What is the latest version of PHP?
What is the full form of PHP?