Search⌘ K
AI Features

"Hello World" Explained

Explore the fundamentals of PHP by writing your first Hello World script. Understand PHP opening and closing tags, how to use echo to display output, the importance of semicolons, and how to add comments to make your code readable and maintainable.

Here’s the code from the previous lesson:

PHP
<?php
echo "Hello, World!\n";
?>

Let’s take a look at this in detail.

We’ll start from the very first line and go step by step!

PHP Opening Tag

A PHP script can be written anywhere in the document, and it signifies the start of the PHP code.

echo

PHP uses a built-in function called echo in order to display one or more strings.

Tip: The echo function is faster than the print() function.

Note: You may use parentheses with the echo function as echo ("string"); but it isn’t compulsory because echo isn’t really a function.

PHP Closing Tag

The PHP closing tag marks the end of the PHP code. It is written as:

Note: All code in PHP is written between the starting (<?php) and ending (?>) symbol. However, the closing tag of a PHP code block at the end of a file is optional. The code would still execute properly even if the closing tag is missing.

Semicolons

Statements in PHP must be terminated with a semicolon.

  • Just as sentences in English must be terminated with a period.
  • Just as sentences in English can span several lines, so can the statements in PHP.

You can use as many spaces and newlines between the start and end symbol of a PHP program as you wish. It helps beautify your code just as spaces are used to align the text printed on the pages of a book.

Comments in PHP

Comments in PHP are used to explain code and make it easier to read. PHP ignores comments when executing the program.

PHP supports single-line comments and multiple-line comments.

A single-line comment can be written using // or #:

<?php
// This is a single-line comment
# This is also a single-line comment
echo "Hello, World!\n";
?>

A multiple-line comment is written using /* and */:

<?php
/* This is a
multiple-line comment */
echo "Hello, World!\n";
?>

Comments are useful when you want to describe what a piece of code does or temporarily disable a line while testing.

Now that we have learned the basics of PHP syntax, let’s take a quick quiz in the next lesson.