Variables & Data Types

Every PHP variable starts with a dollar sign, needs no upfront type declaration, and can hold a different kind of value at different points in its life — PHP figures out the type from whatever you last assigned it.

Declaring a variable

A variable comes into existence the moment you assign to it — there's no separate declaration step:

PHP variables.php
<?php
$name = "Priya";
$age = 29;
$height = 1.68;
$isStudent = false;

echo "$name is $age years old.\n";
echo "Height: $height, student: ";
var_dump($isStudent);
?>
Output
Priya is 29 years old.
Height: 1.68, student: bool(false)

var_dump() is a debugging tool that prints both a value and its type — here it shows bool(false) rather than just false, which becomes useful once values get less obvious. Also notice "$name is $age years old.\n": double-quoted strings automatically substitute variables that appear inside them, a feature called interpolation, covered fully in the next lesson.

PHP's scalar types

PHP has four scalar (single-value) types, plus arrays and objects covered in later lessons:

PHP types.php
<?php
$count = 42;             // int
$price = 19.99;          // float
$label = "widget";       // string
$inStock = true;         // bool

echo gettype($count) . "\n";
echo gettype($price) . "\n";
echo gettype($label) . "\n";
echo gettype($inStock) . "\n";
?>
Output
integer
double
string
boolean

gettype() reports float as "double" for historical reasons (PHP stores floats as C doubles internally) — you'll see both names used depending on the context.

Loose typing and type juggling

PHP is loosely typed: a variable's type isn't locked in, and PHP will automatically convert between types when an operation calls for it — a behavior called "type juggling":

PHP juggling.php
<?php
$x = "5";
$y = 10;
$sum = $x + $y;

echo $sum . "\n";
echo gettype($sum) . "\n";

$x = 5;
$x = "now a string";
echo gettype($x) . "\n";
?>
Output
15
integer
string

"5" + 10 converts the numeric string "5" to an integer before adding, producing 15 as a real int — not the string concatenation you might expect from a language like JavaScript. And because PHP variables aren't locked to a type, reassigning $x to a string later in the same script is completely legal; gettype() just reports whatever it currently holds.

Note: variable names are case-sensitive ($name and $Name are different variables) and must start with a letter or underscore — $1st is a syntax error, $first or $_1st are fine. This trips people up more than any other naming rule in PHP.