← Вернуться к курсу: PHP from scratch

Printing data, comments and week 1 practice

Видео скоро появится

This lesson closes the first week. We will learn the different ways to show information, document code with comments and put everything together in a small program. Printing data is what you will use most to check that your code does what you think, so it is worth mastering the tools PHP offers and knowing which one to use in each case.

echo, print, printf and debugging functions

echo is the usual statement and accepts several arguments separated by commas. print does almost the same but returns 1 and takes only one argument; it is rarely used. printf lets you format with placeholders: %s for text, %d for integers and %.2f for decimals with two digits. For debugging, print_r shows arrays in a readable way and var_dump also shows the types. Neither should be left on a published site.

php
<?php

$product = 'Notebook';
$price = 12.5;
$units = 4;

echo 'Product: ', $product, "\n";
printf("%s costs %.2f each, %d units\n", $product, $price, $units);
printf("Total: %08.2f\n", $price * $units);   // Total: 00050.00

$data = ['name' => $product, 'price' => $price];
print_r($data);
var_dump($data);

$line = sprintf('%05d', 42);  // sprintf returns the text instead of printing
echo $line . "\n";           // 00042

sprintf works like printf but returns the text instead of printing it, ideal for storing it in a variable. A very practical trick in the browser: wrap print_r with pre tags to keep the line breaks. And for long multi-line texts there is the heredoc syntax, which keeps the layout and allows variable interpolation.

php
<?php

// Single-line comment
# Also a single-line comment (less common)
/*
   Multi-line comment.
*/

/**
 * Doc comment: describes code for people and editors.
 */
$name = 'Marta';
$city = 'Lima';

echo <<<TEXT
Name: $name
City: {$city}
The closing marker must be alone on its line.
TEXT;
echo "\n";

Useful comments

Comments are for people: PHP ignores them. There are three styles, with a double slash, with a hash sign or with slash and asterisk for several lines. A good comment explains the why of a decision, it does not repeat what the code already says. A comment like 'add 1 to i' is noise; one like 'the API counts from 1, so we add' is valuable. They are also useful to temporarily disable a line while testing.

Input from the terminal

Although PHP lives on the web, it also works as a console script. The readline function asks the user for text and returns what they type always as a string, even if it is numbers. That is why you must convert with a cast before calculating. This lets us practice without forms, which arrive in week 5.

php
<?php

$name = readline('Your name: ');
$year = (int) readline('Year of birth: ');

$age = (int) date('Y') - $year;

printf("Hello %s, you are about %d years old.\n", trim($name), $age);

When you finish the exercise, answer the week's quiz. If you miss a question, go back to the matching lesson and repeat the examples typing them yourself, without copy and paste. Muscle memory from typing is an important part of learning a new language.

Проверьте себя

Вопрос 1 из 7

Where does PHP code run?

✎ Мои заметки

Сохранено только в этом браузере. Войдите, чтобы хранить в аккаунте.0/5000 символов

← НазадДалее →