Hello World
That edit-run-observe loop is the foundation for every later lesson. Variables, functions, web requests, databases, frameworks, and tests add more moving parts, but PHP still has to read source code and perform its instructions.
Create The Smallest Useful Script
Create a file named hello.php:
<?php
echo "Hello, PHP!\n";
Run it from the directory containing the file:
php hello.php
Expected output:
Hello, PHP!
The command has two important inputs. php selects the PHP command available through your shell, and hello.php identifies the source file that PHP should execute. If the file is in another directory, either move to that directory or provide the correct path.
The terminal command is not part of the PHP file. Do not paste php hello.php beneath the PHP code. The shell runs the command; PHP interprets the contents of the file.
Know What The Command Line Is Testing
This first script runs through PHP's command-line interface. That means there is no browser, web server, URL, HTML document, request method, session, or database involved. PHP starts, reads the file you named, runs the statements in order, writes output to the terminal, and then exits. Keeping the environment that small makes the result easier to reason about.
The command also depends on your shell's current directory. When you type php hello.php, the shell does not search your whole computer for a file with that name. It asks PHP to open hello.php relative to the directory where the command is running. If your editor shows the file but the terminal says it cannot be opened, first check whether the editor and terminal are looking at the same project folder.
If php itself is not found, that is a setup problem rather than a source-code problem. Confirm that PHP is installed and available on your PATH, then rerun the same script without changing the file. Separate environment problems from program problems whenever you can; otherwise you may edit correct PHP code while the actual failure is the command used to run it.
Confirm Which PHP You Are Running
Many systems can have more than one PHP installation. An operating system package, a local development bundle, a container, and an editor extension can each point at a different executable. Before blaming a first script, ask the terminal which runtime it will use:
php -v
The command prints the PHP version and build information. The exact version is not important for this lesson, but the command should prove that PHP starts successfully. If it fails, fix the installation or shell configuration before editing hello.php.
On macOS and Linux shells, you can usually see the executable path with:
command -v php
On Windows PowerShell, use:
Get-Command php
These commands are environment checks, not PHP source code. They help you answer "Which program is the shell launching?" separately from "What does my script print?" That separation matters when an editor's integrated terminal behaves differently from a system terminal, or when a project later uses a containerized PHP runtime. In this first lesson, use the same terminal for the version check, the lint command, and the script run so all three observations refer to the same PHP executable.
Save Plain Source, Not A Document
PHP reads a text file. The file should contain the characters you typed for the program, not formatting information from a word processor and not a screenshot or exported document. A good editor saves hello.php as plain text with the .php extension. The extension is not magic by itself, but it helps editors choose PHP highlighting and helps people recognize the file's purpose.
Be precise about the filename. hello.php, hello.php.txt, and Hello.php can be three different names depending on the operating system and filesystem. If the terminal reports that it cannot open the file, compare the exact spelling shown by your editor with the exact spelling used in the command. On case-sensitive systems, Hello.php does not match hello.php.
Also make sure the file is saved before each run. Many editors show an unsaved-change marker in the tab or title bar. PHP executes the bytes currently stored on disk; it cannot see an editor buffer that has not been saved yet. When output seems unchanged after an edit, save the file, rerun the same command, and then investigate the path if the result is still stale.
These details may feel mechanical, but they protect the feedback loop. Before blaming PHP syntax, confirm that the runtime received the file you meant to test.
Read The Program One Token At A Time
This short script contains several language elements:
<?php
echo "Hello, PHP!\n";
<?php opens PHP code. The next lesson examines tags and complete script structure in more detail.
echo is a PHP language construct that writes values to the current output. In a CLI program, that output normally appears in the terminal.
"Hello, PHP!\n" is a string literal. The double quotes mark where the string begins and ends. The characters between them are the data to print, except that \n is interpreted as a newline.
The semicolon ends the statement. PHP uses semicolons to separate most statements. A newline in the source file makes code easier to read, but it does not normally replace the semicolon.
Source Lines And Output Lines Are Different
The way code is arranged in a file does not automatically determine the output layout. This program has two source lines containing echo, but no output newline:
<?php
echo "first";
echo "second";
It prints:
firstsecond
PHP executes the first statement and writes first. It then executes the second statement and writes second immediately after it. The source-code line break between the statements is for the programmer; it is not printed.
Add newlines to the output explicitly:
<?php
echo "first\n";
echo "second\n";
Now the output is:
first
second
This distinction matters whenever a program generates text, CSV, logs, command output, or an HTTP response. Output formatting must be part of the program's contract rather than an assumption based on how the source looks.
Use Escape Sequences Deliberately
Inside a double-quoted string, a backslash can introduce an escape sequence. Common examples include:
\nfor a newline;\tfor a horizontal tab;\"for a double-quote character;\\for one literal backslash.
For example:
<?php
echo "Course:\tPHP Basics\n";
echo "Message: \"It works\"\n";
echo "Windows-style example: C:\\php\\hello.php\n";
The output is:
Course: PHP Basics
Message: "It works"
Windows-style example: C:\php\hello.php
The visual width of a tab depends on the terminal, so do not use tabs when exact column alignment is important. Later code can use formatting functions when output needs a strict shape.
PHP also provides the PHP_EOL constant for the platform's conventional end-of-line sequence:
<?php
echo 'Hello, PHP!' . PHP_EOL;
The dot joins strings in PHP. This lesson mostly uses \n because it is easy to see inside a literal and works well for course CLI examples. PHP_EOL is useful when deliberately producing platform-native text files. Protocol formats can require a specific newline regardless of the operating system, so choose according to the output contract rather than habit.
Understand Single And Double Quotes
Both single and double quotes can create strings, but escape handling differs:
<?php
echo "one\ntwo\n";
echo 'three\nfour' . PHP_EOL;
The double-quoted string interprets \n, so one and two appear on different lines. The single-quoted string prints the backslash and n as ordinary characters; only the appended PHP_EOL creates a final line ending.
Expected output:
one
two
three\nfour
For now, use double quotes when the string intentionally contains escapes such as \n. Use either style consistently for ordinary text, and make sure the opening and closing quote characters match.
Do not use typographic "smart quotes" copied from a word processor. PHP source requires ordinary straight quote characters such as ' and ".
Print More Than One Value
echo can receive multiple comma-separated values:
<?php
echo 'Hello', ', ', 'PHP', '!', PHP_EOL;
It prints one continuous line:
Hello, PHP!
This is different from putting commas inside one string: the commas between values are PHP syntax and are not printed. Only the comma inside ', ' appears in the output.
A beginner script is often clearer when each echo describes one complete output line. Multiple values become more useful once later lessons introduce variables and calculations.
Add Comments That Explain Intent
A line beginning with // is a single-line comment:
<?php
// Confirm that this file was executed.
echo "Hello from hello.php\n";
PHP ignores the comment during execution. Comments are useful for explaining a non-obvious decision, recording an expected result in a course example, or temporarily orienting the reader.
A comment does not print anything. This code has no output:
<?php
// echo "This line does not run.\n";
Do not use comments to keep large amounts of abandoned code. Version control is the better place to preserve previous implementations. In a first exercise, a short expected-output comment can help you compare behavior without confusing it with executable code.
Prove You Ran The File You Edited
A common early mistake is editing one file and executing another file with the same name. Make the output temporarily identify the source:
<?php
echo "Marker: hello lesson version 2\n";
Run the command again. If the marker does not appear:
- inspect the terminal's current directory;
- list the files in that directory;
- check the command's filename and spelling;
- save the editor buffer;
- check whether another PHP process or browser page is involved.
Use an absolute path when location is uncertain:
php /full/path/to/hello.php
On Windows, the equivalent path may look like C:\projects\php-course\hello.php. The exact path syntax differs, but the principle is the same: remove ambiguity about which source file PHP receives.
Predict Before Running
Do not use the runtime only as a guessing machine. Read a small script from top to bottom, write down the output you expect, then run it:
<?php
echo "A";
echo "B\n";
echo "C\nD\n";
Prediction:
AB
C
D
The first two statements contribute to the same output line because the first string has no newline. The final statement contains two newline escapes and therefore prints two visible lines.
Prediction builds a mental model. When actual output differs, compare the first point where your model and PHP's behavior diverge.
Read Parse Errors As Evidence
This file is invalid because the first string is missing its closing quote:
<?php
echo "Hello, PHP!\n;
echo "Second line\n";
PHP cannot execute an incomplete program. It reports a parse error and a line number. The reported line is where the parser could no longer continue, not always where the mistake began. Inspect that line and the line immediately before it.
Common causes in a first script include:
- a missing semicolon;
- an opening quote with no matching closing quote;
- mismatched single and double quotes;
- a mistyped opening PHP tag;
- command text accidentally pasted into the source file.
When an error message is confusing, simplify the file before trying clever fixes. Leave the opening tag in place, delete everything after it, and add back one echo statement that you understand:
<?php
echo "test\n";
If that file parses and prints test, PHP itself is working and the problem is in the code you removed. Add the next statement back, save, lint, and run again. This is slower than guessing for one edit, but faster than changing quotes, semicolons, filenames, and commands all at once.
Do not ignore the exact line PHP reports, but do not treat it as the only possible source of the problem. A missing quote on one line can make the following line look broken because PHP is still trying to finish the earlier string. Read upward until you find the first place where the source no longer has a complete statement.
Run a syntax-only check with:
php -l hello.php
A successful lint says that PHP can parse the file. It does not prove that the output is correct, so run the script and compare the result too.
Keep The First Feedback Loop Small
Use this sequence whenever you change the script:
- make one intentional edit;
- save the file;
- predict the new output;
- run
php -l hello.phpwhen syntax is uncertain; - run
php hello.php; - compare expected and actual output;
- read the first error before making another change.
Changing several unrelated things at once makes it harder to know which change caused a result. Small iterations produce clearer evidence and make errors easier to repair.
Keep A Clean Terminal Transcript
When you are learning, the terminal is part of the evidence. A useful transcript shows the command you ran, the output PHP produced, and any error message that appeared. It should not mix several experiments together so tightly that you can no longer tell which output belongs to which command.
Before rerunning a script, make sure you know what changed. If you edited hello.php, run the same command again and compare the new output with the previous output. If you also renamed the file, changed directories, or opened a different terminal tab, you have added another possible cause. Those changes may be necessary, but they should be deliberate.
This habit also helps when asking for help. "It does not work" gives another developer very little to inspect. A compact transcript such as "I ran php -l hello.php, it reported no syntax errors, then php hello.php printed Hello PHP! without the comma" points directly at the remaining mismatch. The syntax is valid; the output contract is wrong.
Do not paste passwords, real tokens, or private paths into shared transcripts. For this first lesson, the files and output are harmless, but the same discipline applies later when scripts read configuration or connect to services. Share the smallest command and output that demonstrate the problem.
Separate Output From The Shell Prompt
When a final newline is missing, the next shell prompt can appear directly after the program text. That prompt is not PHP output. Add a newline, rerun the command, and compare only the text produced between command invocation and the next prompt. This simple boundary prevents confusion when checking exact output.
Compare Exact Characters
Early programs are small enough that exact output should be checked character by character. Hello, PHP! and Hello PHP! are different strings because one contains a comma. Hello, PHP! and hello, PHP! are different because one letter has a different case. Hello, PHP! has an extra trailing space that may be hard to see in a terminal, but it is still part of the output.
That precision is not pedantry. Computers compare text literally unless a program is written to ignore differences. A later test may expect one newline at the end of a line, a CSV export may require commas in exact positions, and an API response may be invalid if punctuation or whitespace changes the data format. This first script is a low-risk place to practice the habit.
When output is hard to inspect visually, make the program print obvious boundaries around it:
<?php
echo "[" . "Hello, PHP!\n" . "]";
The newline now appears before the closing bracket:
[Hello, PHP!
]
This technique is useful while debugging, but remove the temporary markers once you understand the result. The final program should print the requested output, not extra helper characters added for inspection.
Notice Success And Failure Signals
The visible text is not the only result of a command-line program. A PHP process also finishes with an exit status. A script that parses and runs normally exits successfully. A script with a parse error, missing file, or fatal runtime error exits unsuccessfully. You do not need to memorize shell-specific commands for checking the status yet, but you should understand why tools care about it: editors, test runners, build scripts, and deployment steps use success or failure to decide what should happen next.
For this first lesson, treat output and status as two related questions:
- did PHP run the file without reporting an error?
- did the program print the exact text you expected?
A script can answer the first question correctly and still fail the second. For example, echo "Hello PHP!\n"; is valid PHP, but it does not match Hello, PHP! because the comma is missing. A script can also fail before output comparison matters, as when a quote is unmatched and PHP cannot parse the file at all.
When checking an exercise, handle failures in that order. First make the file parse. Then make sure the intended file runs. Then compare the output character by character, including spaces, punctuation, and final newlines. This habit scales directly to automated tests later in the course: a test is usually a precise statement about both whether code ran successfully and what result it produced.
Do Not Add A Browser Yet
PHP is often used to build web pages, so it is natural to wonder why the first program runs in a terminal instead of a browser. The reason is control. A command-line script removes the web server, URL routing, HTTP headers, HTML rendering, cookies, sessions, and browser caching from the experiment. If the output is wrong, you only have to inspect the file, the command, and the PHP error message.
The same PHP language is involved when code later runs through a web server, but the surrounding environment changes. In a browser-based request, output may become part of an HTML response. Whitespace can be collapsed by the browser rendering rules. A server may choose which PHP file to execute based on configuration. Errors may be logged somewhere instead of appearing directly on screen. Those are important topics, but they make a first syntax mistake harder to diagnose.
For now, use the CLI as a small laboratory. It lets you practice exact text output before presentation layers are introduced. When you type echo "Hello, PHP!\n";, the terminal shows the characters produced by the program with very little interpretation. That makes it easier to notice whether a comma, space, quote, or newline is present.
This does not mean command-line PHP is only for beginners. Real projects use CLI scripts for migrations, scheduled jobs, import tools, report generation, queue workers, and maintenance commands. The first lesson uses the same mode because it gives clear feedback. Once you can confidently run and explain a tiny CLI script, adding a browser later becomes a change in environment rather than a mystery about the language itself.
What You Should Be Able To Do
After this lesson, you should be able to create and run a PHP file, explain the role of <?php, echo, string quotes, escape sequences, and semicolons, predict multi-statement output, distinguish source formatting from output formatting, lint a file, and verify that you executed the file you edited.
The goal is not merely to reproduce Hello, PHP!. It is to establish a reliable way to turn a small source change into an observed, explainable result.
Practice
Practice: Print A Three-Line Introduction
Name: <your name>
Course: PHP From Zero
Status: first script complete
Requirements
- open PHP code with
<?php - use at least two separate
echostatements - replace
<your name>with your name - include a newline after every output line, including the final line
- end every
echostatement with a semicolon - do not use variables, arrays, HTML, or functions
Before running the script, write down the exact output you expect. Then run:
php -l name.php
php name.php
Record both command results. Finally, explain how you confirmed that the final line ends before the next shell prompt appears.
Show solution
This version uses one echo for the first line and a second echo with multiple values for the remaining lines.
<?php
echo "Name: Ada Lovelace\n";
echo "Course: PHP From Zero\n", "Status: first script complete\n";
Replace Ada Lovelace with your own name.
The syntax check should report:
No syntax errors detected in name.php
Running the file should print:
Name: Ada Lovelace
Course: PHP From Zero
Status: first script complete
Each string ends with \n, including the status line. After that final newline, the terminal displays its next prompt on a new line instead of attaching it to complete. The lint result proves the file can be parsed; comparing the three output lines separately proves the script performs the intended work.
Practice: Change, Save, And Prove The Rerun
Create message.php with output that identifies both the file and a version marker.
First Run
Make the script print exactly:
File: message.php
Marker: version 1
PHP is running!
Lint and run the file. Record the output.
Second Run
Change only the marker to version 2, save the file, and run it again. The second output must contain version 2 and must not contain version 1.
Requirements:
- use strict, literal output only; do not introduce variables yet
- include a newline after every line
- run the same filename both times
- keep the command and observed output for each run
Afterward, list three checks you would make if the terminal continued to show version 1 after the edit.
Show solution
<?php
echo "File: message.php\n";
echo "Marker: version 1\n";
echo "PHP is running!\n";
Run:
php -l message.php
php message.php
First output:
File: message.php
Marker: version 1
PHP is running!
Change only the marker string:
<?php
echo "File: message.php\n";
echo "Marker: version 2\n";
echo "PHP is running!\n";
Second output:
File: message.php
Marker: version 2
PHP is running!
If the old marker remains, first confirm that the editor saved the file. Next confirm that the terminal is in the expected directory and that php message.php names the edited file. Finally, use an absolute file path to remove ambiguity. The marker turns a vague stale-output problem into a concrete test of which file version executed.
Practice: Predict Exact Output
<?php
echo "A";
echo "B\n";
echo "Course:\tPHP\n";
echo "Message: \"ready\"\n";
echo 'Literal: one\ntwo', PHP_EOL;
echo "Done\n";
Verification
- Write your prediction in a
textcode block. - Explain why
AandBshare one line. - Explain why
one\ntworemains visible instead of becoming two lines. - Run
php -land then execute the file. - Compare the first character where your prediction differs from the actual output, if any.
Do not change the script until after recording the first prediction and run.
Show solution
AB
Course: PHP
Message: "ready"
Literal: one\ntwo
Done
A has no newline, so the next echo writes B immediately after it. The \n following B then ends that combined line.
The double-quoted course string interprets \t as a tab. The exact visual width depends on the terminal, but PHP appears after one tab character. The escaped \" sequences print ordinary double-quote characters around ready.
The Literal string uses single quotes, so its backslash and n remain visible characters. The separate PHP_EOL value ends that line. The final double-quoted string interprets its \n, leaving the next shell prompt on a new line.
This exercise is about output bytes and boundaries, not just the words. A prediction such as A B or two lines for one and two would reveal a mistaken model of when PHP emits whitespace.
Practice: Repair Syntax And Output
Save the following intentionally broken source as broken-lines.php. It is shown as text because it is not valid PHP yet.
<?php
echo "first\n";
echo "second\n"
echo 'third\n';
The intended output is:
first
second
third
Task
- Run
php -l broken-lines.phpand record the parse error. - Fix the syntax error without changing the intended words.
- Run the syntax check again and confirm it succeeds.
- Execute the script and identify the remaining output bug.
- Fix that output bug so all three words appear on separate lines.
- Run the lint and execution commands one final time.
Afterward, explain why the parser may report the third echo even though the missing character belongs to the previous statement, and why the single-quoted third\n is syntactically valid but behaviorally wrong for this task.
Show solution
The second echo is missing its semicolon. After adding it, the file becomes valid PHP, but the third line still prints a visible \n because that escape is inside a single-quoted string.
The complete correction is:
<?php
echo "first\n";
echo "second\n";
echo "third\n";
The final syntax check should report:
No syntax errors detected in broken-lines.php
The final execution output is:
first
second
third
PHP reaches the third echo while still expecting the previous statement to end, so the parser can identify the later token as the point where the grammar becomes impossible. The cause is still the absent semicolon after "second\n".
After that repair, 'third\n' is legal PHP. Its behavior is wrong only because single-quoted strings do not interpret \n as a newline. Changing that literal to double quotes makes the requested line break part of the output.