Hello World
Explore how to write your first PHP Hello World program using the echo function. Understand setting up a local server with XAMPP, PHP opening and closing tags, and basic syntax to display output on the screen.
We'll cover the following...
Get started with PHP: Hello World
Now that we know a bit more about PHP, let’s get into writing our first Hello World program. Hello World is a simple program that developers write as their first program with a new language. You can either follow along on your own PHP editor (see below), or you can use Educative’s built in code environment.
To do this on your own, you’ll need:
Text Editor (Notepad, Sublime etc.)
XAMPP for setting up our personal web server
If you’d prefer not to download anything right now and would rather follow along with Educative’s coding environment, skip to the “Hello World in PHP” section below.
Setting up your XAMPP server
Once you’ve downloaded XAMPP, we’ll need to set up a server. To do that, go to the directory where you installed XAMPP, usually found at C:\xampp. Then go to the folder called htdocs and create a folder inside it called MySite. This file path will act as your Local URL for the rest of the project. You’ll save all site-related files here like .html, .php, etc.
Now that we have our folder set up, open your text editor and save a file to that folder called index.php. You’ll write the Hello World example outlined below in this file.
Hello World in PHP
For your first line, type the line:
<?php>
This is the PHP opener tag. This tag can be placed anywhere in a document to signify that the code that comes after is PHP.
For your second line, write:
echo “Hello, world!”;
This calls the built in echo function. This function tells the program to print anything that follows within the quotations, in this case Hello, world!. The echo command can also take variables to print, which we’ll learn more about later.
Lines that express an action being carried out, like calling the echo function with a parameter, are called statements. Each statement in PHP must be concluded with a semicolon to mark where the statement ends.
Finally, write the line:
?>
This is PHP’s closing tag that marks the end of the document’s PHP code section. Any code past this tag will not be treated as PHP and may result in errors.
Here’s what our document will look like by the end, it will print “Hello, World!”:
The most widely used language construct to print output in PHP is echo.
Alternatively, you can also use print:
PHP also provides C-style printf and related functions. Run the following code:
Now in the next lesson, we will discuss the syntax of the “Hello World!” code in detail to get you familiarized with the basic syntax in PHP.