- How To Write Your First PHP Program
- Prerequisites
- Writing the “Hello, World!” Program
- Running the “Hello, World!” Program
- Working Outside the PHP Code Block
- Adding Comments in PHP
- Using DocBlocks for Documentation
- Conclusion
- Tutorial Series: How To Code in PHP
- PHP Hello World
- PHP Hello World on the web browser
- PHP Hello World on the command line
- Summary
How To Write Your First PHP Program
The “Hello, World!” program is a classic and time-honored tradition in computer programming. Serving as a complete first program for beginners and a good program to test systems and programming environments, “Hello, World!” illustrates the basic syntax of programming languages.
This tutorial will walk you through writing a “Hello, World!” program in PHP. You’ll also learn about opening and closing PHP code blocks within your code and using different types of comments in your code.
Prerequisites
You will need PHP installed as well as a local programming environment set up on your computer.
Writing the “Hello, World!” Program
To write the “Hello, World!” program, start by opening a command-line text editor, such as nano , and create a new file:
Once the text file opens up in the terminal window, type out the program:
Let’s break down the different components of the code.
All PHP code falls within a PHP Code Block, starting with .
echo is a language construct. Its arguments are a list of expressions following the echo keyword, separated by commas and not delimited by parentheses. echo tells PHP to display or output whatever is included between echo and the ending semicolon ; .
Between the echo and the ; is a sequence of characters — Hello, World! — that is enclosed in quotation marks. Any characters that are inside quotation marks are called a string.
After writing the program, hold down the CTRL key and press the X key to exit nano . When prompted to save the file, press Y .
Once you exit nano, you’ll return to your shell.
With that, you have written your “Hello, World!” program.
Running the “Hello, World!” Program
With your “Hello, World!” program written, you’re ready to run the program. Use the php command along with the name of the program file as follows:
Running the hello.php program that you just created will cause your terminal to produce the following output:
Let’s go over what the program did in more detail.
PHP executed the line echo «Hello, World!»; by calling the language construct echo . The string value of Hello, World! was passed to the construct.
In this example, the string Hello, World! is also called an argument since it is a value that is passed to another part of the code, such as a construct or a function.
The quotes that are on either side of Hello, World! were not output to the screen because they are used to tell PHP that this section of code contains a string. The quotation marks delineate where the string begins and ends.
Since the program ran successfully, you can now confirm that PHP is properly installed and that the program is syntactically correct. Before going any further in the code itself, let’s take a closer look at the PHP Code Block.
Working Outside the PHP Code Block
Within a .php file, anything outside of the PHP tags is treated as HTML or plain text. The PHP language was originally written as a way to extend the functionality of HTML. With this in mind, you may include multiple PHP code blocks throughout a file. Anything outside the code block will render as HTML or plain text.
Update your hello.php file:
Hi Sammy echo "Hello, World!"; ?> How are you doing? echo "Swimmingly!";
Save the file and rerun it:
OutputHi Sammy Hello, World! How are you doing? Swimmingly!
Diving into the code, you’ll notice that Hi Sammy and How are you doing? are both outside the PHP code blocks and therefore render as plain text when running the program.
This file contains two PHP code blocks. The first code block includes both the starting and ending tags, while the second code block, being at the end of the file, leaves off the final closing tag.
Including the closing block tag ?> is not required. When ending a file with a PHP code block, it is recommended to leave off the closing tag. Any character, even a blank space, which is rendered after the closing tag will be output to the screen as HTML or plain text. This can cause unexpected consequences with the function of your application because certain functionality, such as a redirect, will not process if anything has been output to the browser. When writing a file that contains only PHP code, never include the closing PHP tag.
As code gets more complicated, like when splitting concepts over multiple code blocks, it can be beneficial to leave notes for ourselves and others. You can do this through the use of comments.
Adding Comments in PHP
A comment in code is a line that will not execute as a part of the program. Its only purpose is to be read by a human who is looking at the code. One thing that comes as a shock to many developers is how much time is spent reading code versus writing code. This means it’s essential to have code that is as easy to read as possible. You can accomplish this in a few ways:
- Use coding standards. These are a collection of guidelines and best practices for organizing and formatting code clearly and consistently. In PHP, the most common coding standards are those developed by the PHP-FIG (Framework Interop Group).
- Choose ease of reading over ease of writing. Use descriptive variables over short variables. It’s not about how many lines of code your write, but how long it will take someone to read those lines and understand what’s going on.
- Comment for clarity. While it isn’t a hard and fast rule, if you’ve followed the previous two bullet points, your code should explain what is happening, while the comments explain why something is happening the way it is.
When writing comments in PHP, there are two types of comments: single-line comments and multiline comments. Single line comments can start at any point on a line and end at either the end of the line or the end of the code block, whichever comes first.
The most common way to start a single-line comment is with the double forward slash ( // ), although PHP also recognizes a hash sign ( # ) as a valid start to a single-line comment:
Hi Sammy echo "Hello"; //, World!"; ?> How are you doing? echo "Swimmingly!"; // other options: Floating along
Save the file and run it again:
OutputHi Sammy Hello How are you doing? Swimmingly!
The first comment starts in the middle of a line. A closing quote and semicolon were added after «Hello» and the rest of the line was commented out. Commenting out one or more lines of code is often used in debugging to test how the code responds if certain elements are removed.
You use a second comment to give a secondary option for an answer. The next step in your project may be to respond with one of several different options each time you execute the application. The comment is used as a reminder for other options that could be added.
Multiline comments start with /* and end with */ . The PHP interpreter will ignore any text or code within those characters. To provide more options, let’s change the last line to a multi-line comment:
Hi Sammy echo "Hello"; //, World!"; ?> How are you doing? echo "Swimmingly!"; /* When responding with one of a number of answers, here are some other options: * Floating along * Fin-tastic * Going with the flow * Treading water * Swamped */
Using a multi-line comment gives more room to add detail or formatting to once again make the code, and the intention of the code, easier to understand. This multi-line comment includes line breaks and added * as a delineator for a list. The */ combination signifies the end of our comment block.
Using DocBlocks for Documentation
There is a special type of multi-line comment called a DocBlock. This is a unique way of documenting the functionality of a particular file, class, method, or other structural elements. Although a DocBlock starts and ends like any other multi-line comment /* */ , they are designed to give specific detail for working with an element. Not only do these details provide an overview of the code for developers, but they may also be used by a code editor (or IDE) to provide suggestions and validation.
A DocBlock consists of several parts. The first is a brief summary to introduce the element and a longer description if more context is needed.
The final section that makes a DocBlock unique is for tags and annotations. These provide a way to succinctly and uniformly provide meta-information about the associated element. Tags can, for example, describe the type of information that is accepted or returned by a method or function. It may also provide details about the author or copyright of a file:
/** * DocBlock example * * @author Sammy */ .
While you should strive to write code that is clear and easy to follow, adding clarifying comments can add additional context that will increase the understanding of the code and the choices behind the code.
Conclusion
In this tutorial, you have written the “Hello, World!” program in PHP. You learned about opening and closing PHP code blocks within your code and using different comments to clarify and add context as your code gets more complicated. From here, you can continue learning by following the How To Work with Strings in PHP tutorial.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Tutorial Series: How To Code in PHP
PHP is a popular server scripting language known for creating dynamic and interactive web pages.
PHP Hello World
Summary: in this tutorial, you’ll learn how to execute a script that outputs the Hello, World! message on the web browser and command line.
PHP Hello World on the web browser
First, open the folder htdocs under the xampp folder. Typically, it locates at C:\xampp\htdocs .
Second, create a new folder called helloworld .
Third, create a new file called index.php under the helloworld folder and place the following code in the file:
"en"
> "UTF-8"> "viewport" content="width=device-width, initial-scale=1.0">echo 'Hello, World!'; ?>
Code language: PHP (php)
The code in the index.php file looks like a regular HTML document except the part .
The code between the opening tag is PHP:
echo 'Hello, World!'; ?>
Code language: HTML, XML (xml)
This PHP code prints out the Hello, World message inside the h1 tag using the echo statement:
When PHP executes the index.php file, it evaluates the code and returns the Hello, World! message.
Fourth, launch a web browser and open the URL:
http://localhost:8080/helloworld/
Code language: JavaScript (javascript)
If you see the following on the web browser, then you’ve successfully executed the first PHP script:
If you view the soure code of the page, you’ll see the following HTML code:
html>
html lang="en"> head> meta charset="UTF-8"> meta name="viewport" content="width=device-width, initial-scale=1.0"> title>PHP - Hello, World! title> head> body> h1>Hello, World! h1> body> html>Code language: HTML, XML (xml)
PHP Hello World on the command line
First, open the Command Prompt on Windows or Terminal on macOS or Linux.
Second, navigate to the folder c:\xampp\htdocs\helloworld\.
Third, type the following command to execute the index.php file:
c:\xampp\htdocs\helloworld>php index.php
Code language: CSS (css)
You’ll see the HTML output:
html lang="en">
head> meta charset="UTF-8"> title>PHP - Hello, World! title> head> body> h1>Hello, World! h1> body> html>Code language: HTML, XML (xml)
Since the terminal doesn’t know how to render HTML to web, it just shows the pure HTML code.
To simplify the output, you can use the following code in the index.php :
echo 'Hello, World!';
Code language: HTML, XML (xml)
If you execute the script again:
c:\xampp\htdocs\helloworld>php index.php
Code language: CSS (css)
and you’ll see the following output:
When you embed PHP code with HTML, you need to have the opening tag . However, if the file contains only PHP code, you don’t need to the closing tag ?> like the index.php above.
Summary
- Place the PHP code between to mix PHP code with HTML.
- Use the echo construct to output one or more strings to the screen.