PHP Variables

PHP variables store values such as text, numbers and arrays. Every variable name starts with a dollar sign, and you create it simply by assigning a value. PHP is dynamically typed, so you do not declare a type up front.

Creating PHP Variables

Double-quoted strings replace variables with their values. The dot operator joins strings together.

<?php
$name = "Ayesha";
$age = 28;
$height = 1.65;
$isMember = true;

echo "$name is $age years old.\n";
echo "Height: " . $height . " m";
Ayesha is 28 years old.
Height: 1.65 m

Variable Naming Rules

  • Must start with $ followed by a letter or underscore
  • Can contain letters, numbers and underscores only
  • Cannot start with a number ($1st is invalid)
  • Are case sensitive ($total and $Total differ)
  • Use camelCase or snake_case consistently

Variable Scope

A variable created outside a function is in the global scope and is not visible inside functions. Variables created inside a function are local. Pass values in as parameters instead of relying on globals.

<?php
$site = "naeemamin.cloud";

function show() {
    $local = "inside";
    echo $local . "\n";
    // echo $site; would warn: undefined variable
}
show();

function showSite() {
    global $site;
    echo $site;
}
showSite();
inside
naeemamin.cloud

Static Variables

A static variable inside a function keeps its value between calls. It is useful for simple counters.

<?php
function counter() {
    static $count = 0;
    $count++;
    return $count;
}
echo counter(), counter(), counter();
123

PHP Constants

Constants hold values that never change. Use const at the top level or in classes, or define() when the name is dynamic. Constants have no dollar sign.

<?php
const TAX_RATE = 0.17;
define('APP_NAME', 'Shop');

echo APP_NAME . " tax: " . TAX_RATE * 100 . "%";
Shop tax: 17%

Frequently asked questions

How do you declare a variable in PHP?

Write a dollar sign, a name and assign a value, for example $price = 10;. No keyword or type is needed.

What is the difference between const and define in PHP?

const is evaluated at compile time and works inside classes; define() runs at runtime and can use dynamic names. Both create constants.

How do I use a global variable inside a function?

Use the global keyword or $GLOBALS array, but it is cleaner to pass the value as a function parameter.