PHP Syntax

Last updated on

Understanding PHP syntax is like the basics of any language—PHP syntax defines the rules for writing code that a server can understand, which open and close your scripts. You will also come across options like PHP short tags and the handy PHP shorthand echo, which make your code cleaner and easier to write.

In this tutorial, you will learn basics, from working with the classic PHP tag to understanding the PHP echo shorthand and PHP short tags.

What is PHP Syntax?

PHP syntax refers to the set of rules and guidelines that dictate how PHP code should be written and structured so that it can be correctly interpreted and executed by the server.

It defines how you should open and close PHP scripts, use variables, write functions, and include other elements like loops and conditionals. PHP syntax ensures that your code is understandable to machines.

Standard PHP Tags

PHP script starts and ends with PHP tags:

<?php // Your PHP code goes here ?>

These tags signal to the server that PHP code is being written. There are also PHP short tags (<? ?>) and the shorthand for echo (<?= ?>). Understanding the proper PHP syntax will help you avoid errors in your PHP scripts.

PHP Short Tags

PHP also offers short tags, which look like this:

<? // Your PHP code here ?>

These are not always enabled on all servers, as they require the short_open_tag directive to be turned on in the php.ini configuration file. Because of this limitation, it is best to stick to the standard tags unless you are certain your server supports them.

Shorthand Echo Tag

Another convenient option is the PHP shorthand echo tag:

<?= "Hello, World!" ?>

This is a compact way to write echo statements. if you don't like to use short tags, this shorthand is always enabled, regardless of the server configuration.

ASP-Style Tags (Deprecated)

ASP-style tags resemble tags used in Microsoft's Active Server Pages (ASP). They are written like this:

<% echo "ASP-style tag."; %>

HTML Script Tags (Rarely Used)

PHP code can also be enclosed within an HTML <script> tag, like this:

<script language="php"> echo "This is a script tag."; </script>

Let's see more tags in the PHP language in the following sections.

PHP Echo and Print

When working with PHP echo and print, you will notice that both are used to output text or variables to the browser. While they may seem interchangeable at first glance, there are subtle differences between them that can influence when and how you use each.

echo is a language construct, not a function, which means you can use it without parentheses. It is faster than print when it comes to outputting data.

Here is an example:

echo "Hello, ", "World!", " How are you?";

While print is also a language construct, but unlike echo, it returns a value of 1. This means it can be used in expressions, making it slightly different in functionality.

<?php
  if (print("Hello, World!")) {
     echo " -   Print returned 1";
  }
?>

PHP If Else Shorthand

The PHP if-else shorthand is a concise way to write conditional statements, often used to make your code cleaner and more readable. PHP provides two main shorthand methods: the ternary operator and the null coalescing operator.

The ternary operator is a compact version of an if-else statement. It uses the following syntax:

condition ? value_if_true : value_if_false;

Here is an example:

$is_logged_in = true; $message = $is_logged_in ? "Welcome back!" : "Please log in."; echo $message;

Another point to note is that PHP allows you to omit the middle part (value_if_true) when it is the same as the condition being evaluated. This is known as the shorthand ternary operator:

$value = $condition ?: value_if_false;

Here is an example:

$username = $input_username ?: "Guest"; echo $username;

This was a quick overview of some tags used for statements in PHP. let's see another operator introduced in PHP 7 in the following section.

Null Coalescing Operator

The null coalescing operator (??) is another shorthand for handling conditions, specifically for checking if a variable is set and not null. It is often used as a more readable alternative to isset.

$value = $variable ?? default_value;

Here is an example:

$user_name = $_GET['name'] ?? "Anonymous"; echo $user_name;

Let's see the benefits of using a semicolon in PHP in the following section.

PHP Semicolon

The semicolon (;) is an important part of the language syntax. It acts as a statement terminator, referring to the end of a command or instruction. Without it, the PHP interpreter cannot properly parse your code, leading to syntax errors.

PHP reads code line by line, and the semicolon tells the interpreter where one statement ends and the next begins. This allows you to write clean and structured code, even if multiple statements are on the same line. For example:

echo "Hello, World!"; // Correct usage 
echo "PHP is fun!" // Missing semicolon causes an error 
echo "FlatCoding Tutorials!"; // Correct usage 

The second statement will throw a syntax error because it does not have a semicolon.

Let's see how to write PHP with HTML.

Mixing PHP and HTML

When working on web development projects, you will often find yourself mixing PHP and HTML. This allows you to dynamically generate web pages while keeping the structure and presentation intact.

PHP code is embedded within HTML using PHP tags. The most common tags used are <?php ... ?>, and they can appear anywhere inside an HTML document.

Here is an example:

<!DOCTYPE html>
<html>
<head>
    <title>PHP in HTML</title>
</head>
<body>
    <h1>Welcome to My Website</h1>
    <p>The current date is: <?php echo date('Y-m-d'); ?></p>
</body>
</html>

You can also use PHP to dynamically populate HTML attributes, such as value, href, or class.

<input type="text" value="<?php echo $username; ?>" />
<a href="<?php echo $url; ?>">Visit Profile</a>

If your PHP script needs to output large blocks of HTML, you can write the HTML directly within the PHP tags using echo or by closing the PHP tag temporarily.

<?php
echo '<div class="welcome">';
echo '<h1>Welcome to My Website</h1>';
echo '</div>';
?>

In the following section, you will see a comparison between different PHP tags.

Comparison of PHP Tags

To maintain maximum compatibility and clarity in your PHP code, it is essential to stick to standard PHP tags (<?php ... ?>) for general usage. When working with templates or simple scripts, shorthand echo tags (<?= ... ?>) can be a concise and clear option for output.

However, you should avoid using short tags (<? ... ?>), ASP-style tags (<% ... %>), and script tags (<script language="php"> ... </script>), as they can cause compatibility issues across different server environments.

Tag TypeExampleCompatibilityRecommended?
Standard PHP Tags<?php ... ?>UniversalYes
Short Tags<? ... ?>LimitedNo
Shorthand Echo Tags<?= ... ?>UniversalYes (for output)
ASP-Style Tags<% ... %>DeprecatedNo
Script Tags<script language="php"> ... </script>Rarely SupportedNo

Let's summarize it.

Wrapping Up

You should now have a clear understanding of how PHP syntax and why it is the basis of everything you build in PHP. From opening and closing tags to structuring your scripts with semicolons and embedding PHP in HTML, these basics are your starting point for writing coding. You also learned if-else shorthand, PHP echo vs. print, and the structured elegance of the for loop.

Thank you for reading. To see more PHP tutorials click here. Happy coding!

Frequently Asked Questions (FAQs)

  • What is the correct way to open and close PHP tags?

    You open PHP tags with <?php and close them with ?>. This tells the server where to start and stop reading PHP code.
  • How do you echo a variable in PHP?

    To echo a variable, you can use the shorthand syntax <?= $variable; ?> or the full syntax <?php echo $variable; ?>.
  • What is the difference between echo and print in PHP?

    Both echo and print output data to the screen. The difference is:
    - echo can output multiple variables at once like this echo $var1, $var2;, while print can only handle one argument.
    - print returns a value (1), whereas echo does not.
  • Can I use short tags in PHP?

    Short tags (<?) are discouraged because they may cause conflicts with XML or may not be enabled on some servers. It's safer to use full tags <?php.
  • How do I mix PHP and HTML?

    You can mix PHP and HTML easily. For example:
    <h1>Welcome <?= $username ?>!</h1>
  • What is the shorthand if else in PHP?

    The shorthand for if else is called the ternary operator. Example:
    echo ($condition) ? "True" : "False";
    This is equivalent to:
    if ($condition) { echo "True"; } else { echo "False"; }
  • Why do I need semicolons in PHP?

    Semicolons ; terminate each PHP statement, similar to periods in sentences. Omitting them leads to syntax errors.
  • Should I include the closing PHP tag?

    If you're writing a pure PHP file, it's optional to include the closing tag ?>. It's often omitted to prevent accidental whitespace from being sent to the browser.
  • How do I loop through numbers in PHP?

    You can use a for loop. Example:
    for ($i = 0; $i < 10; $i++) { echo $i; }
    This will print the numbers from 0 to 9.
  • What are PHP short tags and should I use them?

    PHP short tags are <? to open and ?> to close. They are discouraged due to potential conflicts and server settings. Use full tags instead <?php.
Share on: