php language basics

Hello World

Create a file named hello.php:

PHP example
<?php

echo "Hello, PHP!\n";

// Prints:
// Hello, PHP!

Run it from the directory containing the file:

php hello.php

<?php tells PHP where PHP code begins. echo sends text to the output. The text is wrapped in quotes because it is a string, and the semicolon ends the instruction.

The \n at the end of the string is a newline. It moves the terminal cursor to the next line, which keeps command-line output readable.

Printing More Than One Line

PHP executes these instructions from top to bottom:

PHP example
<?php

echo "First line\n";
echo "Second line\n";

// Prints:
// First line
// Second line

Change one of the strings and run the file again. If the old output still appears, check that you edited the same file you are running.

Common First Mistakes

A missing quote or semicolon causes a parse error. Read the file and line number in the error message, then inspect the line immediately before it as well. PHP sometimes notices the problem only when it reaches the next instruction.

For now, keep PHP scripts as simple files run with php filename.php. Later lessons introduce variables, HTML output, and multi-file programs.

Practice

Print Your Name

Create name.php. Use echo to print your name followed by a newline. Run the file with PHP CLI.

Show solution
PHP example
<?php

echo "Amo\n";

// Prints:
// Amo

The newline keeps the next terminal prompt on a separate line. Replace Amo with your own name.

Change The Message

Change the Hello World script so it prints PHP is running! followed by a newline. Run it again and confirm the new output appears.

Show solution
PHP example
<?php

echo "PHP is running!\n";

// Prints:
// PHP is running!

Editing and rerunning the same file is the basic feedback loop you will use throughout the course.

Predict Two Lines
PHP example
<?php

echo "one\n";
echo "two\n";

Then run it and compare the result with your prediction.

Show solution
one
two

PHP runs the first echo, then the second. Each \n moves the output to a new line.

Fix The Newline
PHP example
<?php

echo "first";
echo "second";

Change it so each word appears on its own line.

Show solution
PHP example
<?php

echo "first\n";
echo "second\n";

// Prints:
// first
// second

The newline belongs inside each quoted string.