PHP: PHP Basic Syntax

PHP's syntax borrows from C, Java, and Perl. If you've learned any programming language before, PHP will feel familiar. If you haven't — no worries. This lesson is your starting point.

1. PHP Tags

PHP code must be enclosed in PHP tags so the server can recognize and execute it.

PHP
<?php
// PHP code goes here
echo "Hello World";
?>

(2) Short Echo Tag

PHP
<?= "Hello World" ?>  <!-- Equivalent to <?php echo "Hello World"; ?> -->

<?= ?> is shorthand for <?php echo ... ?> and has been always available since PHP 5.4. It's especially handy for embedding variables in HTML:

PHP
<h1>Welcome, <?= $username ?></h1>
⚠️ Warning: Historically, there was also a <? ?> short tag (without php), but that syntax depends on the short_open_tag setting in php.ini and may not work across different servers. Always use the <?php standard tag.

(3) The Closing ?> Can Be Omitted

If a file contains only PHP code (no HTML), it's recommended to omit the closing ?>:

PHP
<?php
// Pure PHP file — omit the closing ?>
echo "Done";

// End of file — no ?>

Why? To prevent accidental whitespace after ?> from interfering with HTTP headers.


2. Mixing PHP and HTML

One of PHP's most unique features: you can freely mix HTML and PHP in the same file:

▶ Example: PHP Embedded in HTML

Output:

TEXT 📖 Display only
Welcome!
10:30:00
PHP
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>My Site</title>
</head>
<body>
    <h1><?= "Welcome!" ?></h1>
    <p>Current time: <?= date("H:i:s") ?></p>
    
    <?php
    $isLogin = true;
    if ($isLogin):
    ?>
        <p>✅ You are logged in</p>
    <?php else: ?>
        <p>❌ Please log in</p>
    <?php endif; ?>
</body>
</html>

Output:

TEXT 📖 Display only
Output displayed
💡 Tip: PHP offers two styles for mixing with HTML. Use <?= ?> for quick output; wrap larger logic blocks in <?php ... ?>. The alternative syntax for control structures (if (): ... endif;) is more readable than curly braces {}.


3. Statements and Semicolons

Every statement in PHP must end with a semicolon ;:

PHP
<?php
echo "First line";
echo "Second line";
$name = "PHP";
?>

Rules:

🔥 Common Mistake: Forgetting a semicolon is the most frequent beginner error in PHP. The error message is usually Parse error: syntax error, unexpected ... — when you see that, check your semicolons first.


4. Case Sensitivity Rules

PHP has different case-sensitivity rules for different things, which can be confusing:

Type Case-Sensitive? Example
Variable names ✅ Yes $name$Name$NAME
Constant names ✅ Yes MY_CONSTmy_const
Function names ❌ No echo() = ECHO() = Echo()
Class / method names ❌ No MyClass = myclass
Keywords ❌ No if = IF = If

▶ Example: Variables Are Case-Sensitive

PHP
<?php
$color = "red";
$Color = "blue";
$COLOR = "green";

echo $color;  // Output: red
echo $Color;  // Output: blue
echo $COLOR;  // Output: green
?>
▶ Try it Yourself

Output:

TEXT 📖 Display only
Output displayed
💡 Tip: Even though function names and keywords are case-insensitive, always use lowercase. Code consistency matters more than flexibility.


5. Comments

PHP supports three comment styles:

PHP
<?php
// This is a single-line comment (C++ style)

# This is also a single-line comment (Shell style)

/*
 * This is a multi-line comment
 * It can span multiple lines
 * Just like in C
 */

/**
 * This is a documentation comment
 * Used to document functions and classes
 * @param string $name The username
 * @return string A greeting message
 */
function greet($name) {
    return "Hello, " . $name;
}
?>
Style Syntax Notes
Double slash // comment Most common — recommended
Hash # comment Shell style — rarely used
Slash-star /* */ Multi-line comments
Doc comment /** */ For function/class API documentation
💡 Tip: Don't write obvious comments. // Assign 1 to $a is unnecessary — the code already says that. Comments should explain why something is done, not what is done.


6. echo vs. print

Both echo and print are PHP output statements. They're very similar, with subtle differences:

echo print
Multiple arguments echo "a","b","c"; ❌ Only one
Return value ❌ None ✅ Always returns 1
Speed Slightly faster Slightly slower
Usage share 95% echo Rarely used

▶ Example: Using echo

Output:

TEXT 📖 Display only
Hello World
My", " name", " is", " John
<h2>This is a heading</h2>
Hello, Alice
PHP
<?php
// Output a string
echo "Hello World";

// Output multiple (comma-separated)
echo "My", " name", " is", " John";  // Output: My name is John

// Output HTML tags
echo "<h2>This is a heading</h2>";

// Output a variable
$name = "Alice";
echo "Hello, " . $name;  // Hello, Alice

// Double quotes parse variables directly
echo "Hello, $name";     // Hello, Alice
?>

Output:

TEXT 📖 Display only
Output displayed
💡 Tip: Always use echo. Unless you're in a context that requires a return value (extremely rare), you don't need print.


7. Escape Characters

Use the backslash \ to represent special characters in strings:

Escape Sequence Meaning
\n Newline
\r Carriage return
\t Tab
\\ Backslash itself
\$ Dollar sign (prevents it from being treated as a variable)
\" Double quote

▶ Example: Escape Characters

PHP
<?php
echo "Line one\nLine two\nLine three";
// For visible line breaks in the browser, use <br>
echo "Line one<br>Line two<br>Line three";

echo "He said: \"PHP is easy!\"";
echo "The path is C:\\xampp\\htdocs";
echo "The price is \$100";
?>
▶ Try it Yourself

Output:

TEXT 📖 Display only
Output displayed
⚠️ Warning: \n doesn't produce a visible line break in HTML (browsers ignore plain-text newlines). To break a line on a web page, use the <br> tag with CSS styling. \n only affects how the HTML source code looks.

❓ FAQ

Q Why does my .php file show raw source code in the browser instead of executing?
A You probably double-clicked the .php file (which opens it via the file:/// protocol), or the server doesn't have PHP installed/enabled. PHP files must be accessed via http://localhost/.
Q What's the difference between <?php and <?=?
A <?php is the full PHP tag — write any PHP code inside it. <?= ?> is shorthand for <?php echo ... ?> and is only used to output a single expression.
Q Can echo output numbers and strings together?
A Yes. PHP auto-converts types. echo 42 . " is the answer"; outputs "42 is the answer" — the integer 42 is automatically converted to a string.

📖 Summary

📝 Exercises

  1. Create a PHP page that includes your name (using a variable), the current date (using the date function), and an HTML table — all output through echo.
  2. Try all three comment styles — //, #, and /* */ — in the same file and confirm they all work.
  3. Write a comparison example that uses both \n and <br> to understand how they differ in the browser.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏