AnyCompiler

Variables and Types

Every PHP variable name starts with $ — that sigil is not optional punctuation, it's part of the name. $age and age are unrelated; age with no $ is a bare constant-like identifier, not the variable you probably meant. There's no let, var, or type keyword in front of a variable's first assignment — $age = 36; both creates $age and sets it, in one statement, the same minimal style Python and Ruby use.

PHP is dynamically typed: a variable's type is whatever its current value's type is, and reassigning it to a different kind of value is completely normal, not an error. gettype() reports a value's current type as a string; var_dump() is more detailed — it prints both the type and the value together, which is what the rest of this course will reach for whenever a value's exact shape matters.

<?php
$name = "Ada";
$age = 36;
$price = 19.99;
$isStudent = false;

var_dump($name);
var_dump($age);
var_dump($price);
var_dump($isStudent);
echo gettype($age), "\n";

$age = "thirty-six";
echo gettype($age), "\n";
Output
string(3) "Ada"
int(36)
float(19.99)
bool(false)
integer
string

string(3) "Ada" means "a 3-character string"; int(36) and float(19.99) are PHP's two numeric types (float is PHP's name for a double-precision decimal — it also accepts the alias double); bool(false) is PHP's boolean. Then $age — which held the integer 36 a moment ago — was reassigned to the string "thirty-six", and gettype() confirms it: the variable itself has no fixed type, only its current value does. Next: strings — concatenation with ., double-quote interpolation, and the standard library's string functions.

Practice exercise

Create $age = 30, then var_dump($age), then echo gettype($age) on its own line.