Variables & Data Types
PHPVariables are containers for storing data. In PHP, variables start with a $ sign. PHP is a loosely typed language — you don't need to declare a variable's type before using it.
Declaring Variables
PHP
<?php
$name = "John"; // String
$age = 25; // Integer
$price = 9.99; // Float
$isActive = true; // Boolean
$nothing = null; // Null
echo $name; // John
echo $age; // 25
?>
PHP Data Types
| Type | Example | Description |
|---|---|---|
| String | "Hello" | Text — wrapped in quotes |
| Integer | 42 | Whole numbers |
| Float | 3.14 | Decimal numbers |
| Boolean | true / false | True or false value |
| Null | null | No value / empty |
| Array | [1, 2, 3] | List of values |
| Object | new MyClass() | Instance of a class |
Strings
Strings are text wrapped in single or double quotes. Double quotes allow variable interpolation:
PHP
<?php
$name = "Suraj";
// Single quotes - literal string
echo 'Hello $name'; // Hello $name
// Double quotes - variable is replaced
echo "Hello $name"; // Hello Suraj
echo "Hello {$name}!"; // Hello Suraj!
// String concatenation with .
echo "Hello " . $name . "!"; // Hello Suraj!
?>
Integers & Floats
PHP
<?php
$a = 10; // Integer
$b = 3.14; // Float
$c = -5; // Negative integer
$d = 1_000_000; // Underscore for readability (PHP 7.4+)
echo gettype($a); // integer
echo gettype($b); // double (float)
?>
Booleans
PHP
<?php
$isLoggedIn = true;
$hasError = false;
if ($isLoggedIn) {
echo "Welcome!";
}
// var_dump shows the type and value
var_dump($isLoggedIn); // bool(true)
var_dump($hasError); // bool(false)
?>
Null
PHP
<?php
$value = null;
// Check if variable is null
if (is_null($value)) {
echo "Value is null";
}
// isset() returns false if null
echo isset($value) ? "Set" : "Not set"; // Not set
?>
Checking Variable Types
PHP
<?php
$x = 42;
echo gettype($x); // integer
echo is_int($x); // 1 (true)
echo is_string($x); // (empty = false)
var_dump($x); // int(42)
?>
Type Juggling (Type Coercion)
PHP automatically converts types when needed — this is called type juggling:
PHP
<?php
$a = "5"; // String
$b = 3; // Integer
echo $a + $b; // 8 — PHP converts "5" to integer automatically
// This can cause bugs!
echo "5" == 5; // true (loose comparison)
echo "5" === 5; // false (strict — different types!)
?>
💡
Always use
=== for comparisons! PHP's loose comparison (==) can cause unexpected bugs due to type juggling. Use strict comparison (===) to check both value AND type.
Variable Naming Rules
| Rule | Example |
|---|---|
| ✅ Start with $ sign | $name |
| ✅ Letters, numbers, underscores | $user_name |
| ✅ Start with letter or underscore | $_private |
| ❌ Cannot start with number | $1name — invalid |
| ❌ No spaces or special chars | $my-name — invalid |
| ⚠️ Case sensitive | $Name ≠ $name |
Test your knowledge!
Take the PHP Basics quiz to test what you learned.