Lesson contents

PHP — Scalar types and identifiers

PHP values have runtime types. A quoted identifier remains a string, while integer quantities can be multiplied before formatting the result.

A simple example

Tell a number from text

  1. Start with 2 and "2"
  2. Do this Add or join
  3. Result 4 and 22
Adding two numbers gives 4. Joining two copies of the text gives the two characters 22.
lesson.php
<?php
echo 2 + 2, PHP_EOL;
echo "2" . "2", PHP_EOL;
Output
4
22
Advertisements

Choosing a data type

Type or declaration Example Use
string '007' Preserves the original sequence of bytes.
int 125 A signed whole number whose size depends on the platform.
float 0.25 Represents a floating-point value.
bool true Represents a logical outcome.
null null Can represent an absent value. Strict equality distinguishes it from zero.

Keep a product identifier and its price distinct

Keep the printed code 007 as text. Store the quantity and the price in cents as whole numbers so multiplication gives an exact total for this order. Keep the product code out of arithmetic. PHP can interpret numeric strings as numbers in arithmetic contexts, which would discard the written leading zeros.

Product label: 007. Quantity × price: 3 × 125¢. Line total: 375¢.
Keep a product code intact

A school shop sells three packs of paper at 125 cents each. Its scanner must print the code 007 exactly as it appears on the shelf. Keep the code as text and multiply the numeric quantity and price.

Run the example

Use PHP 8.2 or later. Run these commands from the directory containing the example.

php lesson.php
lesson.php
<?php
declare(strict_types=1);

$product = '007';
$quantity = 3;
$priceCents = 125;
$total = $quantity * $priceCents;
printf("%s: %d cents\n", $product, $total);
Output
007: 375 cents

The label retains both leading zeros. Three units at 125 cents cost 375 cents. The display joins the values only after the calculation.

Try it yourself

Change the code to 010 and the quantity to zero. What should stay visible?

Check your answer

The label stays 010 and the total becomes 0 cents. Treating the identifier as a number would lose its written form.

PHP language manual

Related tags

  • PHP
  • data types
  • text
  • integer values