PHP Syntax

PHP syntax is simple and borrows a lot from C and JavaScript. A PHP script starts with <?php and every statement ends with a semicolon. In a file that contains only PHP, you should leave out the closing ?> tag to avoid accidental whitespace in the output.

Basic PHP Syntax

This script prints two lines. echo can print several values separated by commas.

<?php
echo "Line one\n";
echo "Line ", "two", "\n";
print "print works too\n";
Line one
Line two
print works too

PHP Comments

Comments are ignored by PHP. Use them to explain why the code does something.

<?php
// single-line comment
# also a single-line comment
/*
   multi-line comment
*/
/** DocBlock comment used by editors and tools */
echo "Comments are not printed";
Comments are not printed

Case Sensitivity

Keywords and function names are not case sensitive, so ECHO and echo both work. Variable names are case sensitive: $color and $Color are two different variables. Stick to lowercase keywords and consistent variable names.

<?php
$color = "red";
ECHO "My car is $color\n";
echo "My house is " . ($Color ?? "undefined");
My car is red
My house is undefined

Echo vs Print

  • echo has no return value and accepts multiple arguments
  • print returns 1, so it can be used inside expressions, and accepts one argument
  • echo is slightly more common in real code
  • Both are language constructs, so parentheses are optional

Strict Types

Modern PHP files often start with declare(strict_types=1). It makes PHP throw an error when you pass the wrong type to a typed function instead of silently converting it. You will see this line in many professional projects.

<?php
declare(strict_types=1);

function double(int $n): int {
    return $n * 2;
}
echo double(21);
42

Frequently asked questions

Should I close the PHP tag at the end of a file?

For files that contain only PHP, no. Omitting ?> prevents stray whitespace from being sent, which can break headers and sessions.

Is PHP case sensitive?

Partly. Variables are case sensitive, but keywords, functions and class names are not. Write them consistently anyway.

What is the difference between echo and print in PHP?

echo can output several values and returns nothing, while print outputs one value and returns 1. In practice echo is used most.