Values and variables

Print things, and give values names so you can use them again.

Your PHP code runs inside your browser tab. Nothing to install.

Printing a value

A program is a list of instructions that run from top to bottom.

PHP code starts after the <?php line. echo prints. \n inside double quotes ends the line, and each statement ends with a semicolon.

Load the example and press Run. The first run takes a few seconds while PHP loads into your browser.

Example
<?php
echo "Hello\n";
echo 42, "\n";

Naming a value

A variable is a name for a value.

A variable's name always starts with a dollar sign. You create one by giving it a value. echo can print several things separated by commas.

After that, the name can be used wherever the value is needed.

Example
<?php
$name = "Asha";
$marks = 82;
echo $name, "\n";
echo $marks + 5, "\n";

Your turn: a variable

Create a variable and print it.

Practice task

Create a variable called `$city` holding the text Pune, then print it.

Your answer is run and checked in the lesson. Try it now.

Working with numbers

Numbers can be added with +, subtracted with -, multiplied with * and divided with /.

Dividing with / can give a number with a decimal point.

Multiplying and dividing happen before adding and subtracting. Use brackets to change the order.

Example
<?php
$price = 250;
$quantity = 3;
$total = $price * $quantity;
echo $total, "\n";
echo ($total + 50) / 2, "\n";

Your turn: a calculation

Three subjects were marked 82, 67 and 91.

Practice task

Store the three marks 82, 67 and 91 in variables, then print their average: the sum divided by 3.

Your answer is run and checked in the lesson. Try it now.