php language basics

Beginner Milestone: Scripts, Values, And Expressions

PHP example
<?php

const FREE_SHIPPING_THRESHOLD_CENTS = 5_000;

$productName = 'PHP Workbook';
$priceCents = 2_499;
$quantity = 2;

$subtotalCents = $priceCents * $quantity;
$hasFreeShipping = $subtotalCents >= FREE_SHIPPING_THRESHOLD_CENTS;
$shippingLabel = $hasFreeShipping ? 'free' : 'standard';

echo "Item: $productName\n";
echo "Subtotal: $subtotalCents cents\n";
echo "Shipping: $shippingLabel\n";

// Prints:
// Item: PHP Workbook
// Subtotal: 4998 cents
// Shipping: standard

Read the script from top to bottom. The named values make the calculation visible. The subtotal is an integer number of cents, and the comparison produces a boolean used by the short choice at the end.

Change one value at a time and predict the result before rerunning the file. If you can explain why the output changes, you are ready to use the same expressions inside if statements and loops.

Practice

Trace A Cart Total

A notebook costs 750 cents and the quantity is 3. Write a script that calculates and prints the subtotal. Predict the output before running it.

Show solution
PHP example
<?php

$priceCents = 750;
$quantity = 3;
$subtotalCents = $priceCents * $quantity;

echo "$subtotalCents cents\n";

// Prints:
// 2250 cents
Change The Free-Shipping Threshold
Show solution
PHP example
<?php

const FREE_SHIPPING_THRESHOLD_CENTS = 4_500;

$subtotalCents = 4_998;
$shippingLabel = $subtotalCents >= FREE_SHIPPING_THRESHOLD_CENTS ? 'free' : 'standard';

echo "Shipping: $shippingLabel\n";

// Prints:
// Shipping: free
Build An Item Summary

Create variables for a product name, price in cents, and quantity. Print the product name, quantity, and calculated subtotal on separate lines.

Show solution
PHP example
<?php

$productName = 'Pen';
$priceCents = 150;
$quantity = 4;
$subtotalCents = $priceCents * $quantity;

echo "Item: $productName\n";
echo "Quantity: $quantity\n";
echo "Subtotal: $subtotalCents cents\n";

// Prints:
// Item: Pen
// Quantity: 4
// Subtotal: 600 cents