LessonsPHP Basics → Lesson 2

Variables & Data Types

PHP
⏱ 12 min read 📖 Beginner Not completed

Variables 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

TypeExampleDescription
String"Hello"Text — wrapped in quotes
Integer42Whole numbers
Float3.14Decimal numbers
Booleantrue / falseTrue or false value
NullnullNo value / empty
Array[1, 2, 3]List of values
Objectnew 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

RuleExample
✅ 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
← Previous Lesson Next Lesson →
🧠

Test your knowledge!

Take the PHP Basics quiz to test what you learned.

Take Quiz →