Beginner

Hello World in PHP

Your first PHP program - the classic Hello World example with Docker setup

Every programming journey starts with Hello World. Let’s write our first PHP program.

The Code

Create a file named hello.php:

1
2
<?php
echo "Hello, World!\n";

Understanding the Code

  • <?php - The opening tag that tells the server to interpret what follows as PHP code.
  • echo - A language construct that outputs one or more strings. It’s the most common way to output text in PHP.
  • "Hello, World!\n" - A string literal with a newline character at the end.
  • No closing tag - When a file contains only PHP code, it’s best practice to omit the closing ?> tag to avoid accidental whitespace issues.

Running with Docker

The easiest way to run this without installing PHP locally:

1
2
3
4
5
# Pull the official PHP CLI image
docker pull php:8.3-cli-alpine

# Run the program
docker run --rm -v $(pwd):/app -w /app php:8.3-cli-alpine php hello.php

Running Locally

If you have PHP installed:

1
php hello.php

Expected Output

Hello, World!

Alternative Syntax

PHP offers several ways to output text:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
<?php
// Using echo (most common)
echo "Hello, World!\n";

// Using print (similar to echo, but returns 1)
print "Hello, World!\n";

// Short echo syntax (useful in templates)
// Note: Requires short_open_tag or always works with <?=
?>
<?= "Hello, World!\n" ?>

Key Concepts

  1. PHP is interpreted - Code is executed line by line by the PHP interpreter
  2. Designed for the web - PHP was created specifically for web development
  3. Embedded in HTML - PHP can be mixed with HTML in .php files
  4. Flexible typing - Variables don’t require type declarations (though type hints are available in modern PHP)

PHP Tags

PHP code must be enclosed in tags:

1
2
3
4
<?php
// Full opening tag - always works
echo "Hello";
?>

For files containing only PHP code (like libraries), omit the closing tag:

1
2
3
<?php
// No closing tag needed - prevents whitespace issues
echo "Hello, World!\n";

Next Steps

Continue to Variables and Data Types to learn about storing and manipulating data in PHP.

Running Today

All examples can be run using Docker:

docker pull php:8.3-cli-alpine
Last updated: