Variables and Data Types
Variables in PHP start with a dollar sign. The name comes after it, like $name or $total. You assign a value with a single equals sign, and from then on the variable holds that value until you change it. There is no declaring type first; PHP figures it out from what you assign.
PHP has the data types you already know from other languages. Strings are text in quotes, integers are whole numbers, floats are numbers with decimals, and booleans are true or false. There is also null for "no value yet". A variable changes type freely: $x = 5 makes it an integer, and $x = "five" makes it a string on the next line.
Variable names are case-sensitive, so $name and $Name are two different variables. They must start with a letter or underscore, and the rest can be letters, numbers, or underscores. PHP keywords like echo cannot be variable names, but most sensible names work fine.
To see what a variable really holds, use var_dump($variable). It prints the type and the value together, which makes debugging far easier than echo alone. This one function is the closest thing PHP has to a built-in inspector.
Strings in single and double quotes
Double-quoted strings can contain variables and escape codes, and PHP fills them in. Single-quoted strings are literal: what you type is what you get. Beginners find this out the hard way when a $ in a single-quoted string stays as text.
$name = "Aya";
echo "Hello $name"; // Hello Aya
echo 'Hello $name'; // Hello $name (literal)
Changing types on the fly
PHP converts types automatically when you use them together. A number and a string with a number work in math, and a string concatenated with a number just works. This is convenient, but it also hides mistakes, so check types with var_dump when results surprise you.
$price = 12;
$price = $price . ".50"; // now a string: "12.50"
var_dump($price);
// string(5) "12.50"
Syntax
<?php
$name = "Aya";
$age = 24;
$height = 1.65;
$member = true;
$nickname = null;
var_dump($name); // string(3) "Aya"
?>
$name vs $Name Are Different
PHP variables are case-sensitive — $name and $Name are two variables.
$name = "Ada"; // not $Name
Good to know
- Variables start with $ and need no type declaration.
- Double quotes fill in variables; single quotes stay literal.
- Types can change as you reassign a variable.
- var_dump shows the type and value for debugging.