PHP Variables, Types, and Scope

Last updated: August 27, 2026.

PHP variables begin with $ and receive their type from the assigned value. Variable names are case-sensitive, so $total and $Total are different variables.

Assign and use values

<?php
$name = 'Ada';
$itemCount = 3;
$price = 12.50;
$isActive = true;

$total = $itemCount * $price;
echo "{$name}: " . number_format($total, 2);
?>

Inspect and declare types

<?php
declare(strict_types=1);

function invoiceTotal(float $price, int $quantity): float
{
    return $price * $quantity;
}

var_dump(invoiceTotal(14.95, 2));
?>

Variable scope

A variable created inside a function is local to that function. Pass inputs as parameters and return results explicitly.

<?php
$taxRate = 0.08;

function addTax(float $subtotal, float $rate): float
{
    return $subtotal * (1 + $rate);
}

echo addTax(50, $taxRate);
?>

Read external input deliberately

<?php
$page = filter_input(INPUT_GET, 'page', FILTER_VALIDATE_INT);
$page = ($page !== false && $page !== null && $page > 0) ? $page : 1;
?>

Superglobals such as $_GET and $_POST contain untrusted input. Validate values for their intended use and encode them when inserting them into HTML. See PHP variable basics.

admin

admin

Leave a Reply

Your email address will not be published.