iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

PHP Syntax

PHP code lives between <?php ... ?> tags. Everything outside those tags is sent to the browser unchanged.

The tags

PHP
<!DOCTYPE html>
<html>
<body>
  <h1><?php echo 'Hello, world'; ?></h1>
  <p>The time is <?= date('H:i') ?>.</p>
</body>
</html>

<?= $x ?> is shorthand for <?php echo $x; ?>.

Pure PHP files

If a file contains only PHP code, omit the closing ?>. It avoids accidental trailing whitespace that could break headers / output:

PHP — UserService.php
<?php

namespace App;

class UserService
{
    public function ...
}

Statements end with ;

PHP
$name = 'Ada';
echo "Hello, $name";
$age  = 36;

Case sensitivity

ThingCase-sensitive?
Variables ($name)Yes
Functions, methods, classes, keywordsNo — but use the documented case
Constants (by default)Yes

Whitespace is mostly free

PHP doesn't care if you put a statement on one line or three — but the community uses PSR-12. Run php-cs-fixer or pint to format automatically.

Tip: A common bug — forgetting ; at the end of a line — usually shows up as a syntax error pointing at the next line. Look one above.

Example

Example
<?php
$name = 'Ada';
echo "Hello, $name!";
Try it Yourself »

Exercise

Wrap PHP code with the standard opening tag.

echo 'hi'; ?>

Test yourself

Q1. PHP code lives inside…
Q2. <?= $x ?> is shorthand for…
Q3. Pure PHP files…

Discussion

Loading…