Chapter 1

Your First PHP Programs and Reading Errors

Run PHP on purpose rather than by habit. Learn how the interpreter works through your file, and read the errors it gives you as evidence.

Chapter 1, Your First PHP Programs and Reading Errors

What you will learn

  • Run a PHP file from the command line and understand the role of the PHP interpreter.
  • Write output with echo and recognize PHP tags and statement terminators.
  • Distinguish syntax errors, runtime problems, and logic errors.
  • Read an error message before changing code.

The code from this chapter

Type these programs yourself. The predictions below are the exercises; the explanations are in the book.

1.1 How PHP Runs

Type this into a file, predict the output, then run it.

PHP
<?php

echo "PHP is running." . PHP_EOL;

1.2 Statements and Output

Type this into a file, predict the output, then run it.

PHP
<?php

// A comment explains why, not what.
$score = 10;
$Score = 20;   # a different variable

echo "Two values: ", $score, PHP_EOL;
echo $Score . PHP_EOL;

1.3 Three Kinds of Problems

Type this into a file, predict the output, then run it.

PHP
<?php

$total = 10;
$count = 0;

echo $total / $count;

Type this one as well, and predict it before you run it.

PHP
<?php

$width = 7;
$height = 3;
$area = $width + $height;

echo "Area: " . $area . PHP_EOL;

TPRM Lab 1.1: Hello from PHP

Type this into a file, predict the output, then run it.

PHP
<?php

echo "Hello from PHP!\n";
echo "I am learning by running code.\n";

TPRM Lab 1.2: Calculate Before You Print

Type this into a file, predict the output, then run it.

PHP
<?php

$width = 7;
$height = 3;
$area = $width * $height;

echo "Area: " . $area . "\n";

Back to PHP the TPRM Way