php language basics

Variables And Constants

A variable gives a value a name. This lets you reuse a value, print it later, and replace it when the program's state changes.

PHP variable names begin with $:

PHP example
<?php

$productName = 'PHP Workbook';
$priceCents = 2499;

echo "$productName costs $priceCents cents\n";

// Prints:
// PHP Workbook costs 2499 cents

The variable names explain what the values mean. $priceCents is clearer than $price because the unit is part of the name.

Values Can Change

Assignment uses =. You can assign a new value to an existing variable:

PHP example
<?php

$stock = 10;
$stock = 9;

echo "Remaining stock: $stock\n";

// Prints:
// Remaining stock: 9

Choose descriptive names using camelCase. PHP variable names are case-sensitive, so $productName and $productname are different variables.

Constants For Values That Must Stay Stable

A constant has a name but is not meant to change while the script runs. Use const for stable application-level values such as a supported currency or maximum batch size.

PHP example
<?php

const CURRENCY = 'GBP';
const MAX_ITEMS_PER_ORDER = 20;

echo CURRENCY . "\n";
echo MAX_ITEMS_PER_ORDER . "\n";

// Prints:
// GBP
// 20

Constants do not start with $. By convention, constant names are uppercase with underscores.

Use a variable when the value can change during the program. Use a constant when changing the value at runtime would be a mistake.

Practice

Print A Profile Line

Create variables for a person's name and job title. Print a line such as Amo works as a PHP developer. followed by a newline.

Show solution
PHP example
<?php

$name = 'Amo';
$jobTitle = 'PHP developer';

echo "$name works as a $jobTitle.\n";

// Prints:
// Amo works as a PHP developer.
Fix A Variable Name
PHP example
<?php

$customerName = 'Grace';

echo "$customername placed an order.\n";

Explain why PHP treated the two names differently.

Show solution
PHP example
<?php

$customerName = 'Grace';

echo "$customerName placed an order.\n";

// Prints:
// Grace placed an order.

Variable names are case-sensitive. $customerName and $customername are different names.

Build A Settings Line
Show solution
PHP example
<?php

const CURRENCY = 'GBP';

$itemsPerPage = 25;

echo 'Currency: ' . CURRENCY . "; items per page: $itemsPerPage\n";

// Prints:
// Currency: GBP; items per page: 25

The currency is a constant because it is stable for this script. The page size is a variable because a program may change it later.