PHP Variables and Data Types
Understanding variables and data types is fundamental to programming in PHP. This guide covers everything you need to know about working with different types of data in your PHP applications.
What are Variables?
Variables are containers for storing data values. In PHP, variables start with a dollar sign ($) followed by the variable name.
Variable Naming Rules
<?php
// Valid variable names
$name = "John";
$firstName = "Jane";
$first_name = "Bob"; // Snake case
$first_name123 = "Alice";
$_private = "hidden variable";
// Invalid variable names (will cause errors)
// $123name = "invalid"; // Cannot start with number
// $first-name = "invalid"; // Cannot use hyphens
// $first name = "invalid"; // Cannot contain spaces
?>
PHP Data Types
PHP supports several data types, which can be categorized into three groups:
Scalar Types (Single Values)
1. Strings
Strings are sequences of characters:
<?php
// Single quotes
$name = 'John Doe';
$message = 'Hello, World!';
// Double quotes (processes variables)
$greeting = "Hello, $name";
$price = "The price is $19.99";
// Heredoc (for multi-line strings)
$longText = <<<HTML
<div class="card">
<h2>$name</h2>
<p>This is a multi-line string.</p>
</div>
HTML;
// Nowdoc (like single quotes, no variable processing)
$template = <<<'TEXT'
Hello {name}, this is a template
TEXT;
// String functions
$text = "Hello World";
echo strlen($text); // 11
echo strtoupper($text); // HELLO WORLD
echo strtolower($text); // hello world
echo ucfirst($text); // Hello world
echo ucwords($text); // Hello World
echo str_replace("World", "PHP", $text); // Hello PHP
echo strpos($text, "World"); // 6
echo substr($text, 0, 5); // Hello
?>
2. Integers
Integers are whole numbers:
<?php
$age = 25;
$temperature = -5;
$population = 7800000000;
$hexValue = 0xFF; // 255 in hexadecimal
$octalValue = 077; // 63 in octal
$binaryValue = 0b1010; // 10 in binary
// Integer functions
echo abs(-10); // 10 (absolute value)
echo round(3.7); // 4 (rounding)
echo ceil(3.2); // 4 (round up)
echo floor(3.9); // 3 (round down)
echo pow(2, 3); // 8 (exponentiation)
echo sqrt(16); // 4 (square root)
echo max(1, 5, 3); // 5 (maximum)
echo min(1, 5, 3); // 1 (minimum)
?>
3. Floats (Doubles)
Floats are numbers with decimal points:
<?php
$price = 19.99;
$temperature = 98.6;
$scientific = 1.23e-4; // 0.000123
$negative = -3.14;
// Math functions
echo pi(); // 3.1415926535898
echo is_nan(sqrt(-1)); // 1 (true, not a number)
echo is_finite(1/0); // 0 (false, infinite)
echo is_infinite(1/0); // 1 (true, infinite)
?>
4. Booleans
Booleans represent truth values:
<?php
$isLoggedIn = true;
$hasPermission = false;
$isActive = True; // Case insensitive
$isEmpty = FALSE;
// Values that evaluate to false
$falseValues = [
false,
0,
0.0,
"",
"0",
[],
null
];
// Values that evaluate to true
$trueValues = [
true,
1,
-1,
"hello",
[1, 2, 3]
];
// Type casting
$bool = (bool) 1; // true
$bool = (bool) 0; // false
$bool = (bool) ""; // false
$bool = (bool) "hello"; // true
?>
Compound Types
1. Arrays
Arrays store multiple values:
<?php
// Indexed arrays
$fruits = ["apple", "banana", "orange"];
$numbers = array(1, 2, 3, 4, 5); // Old syntax
$mixed = [1, "hello", true, 3.14];
// Access elements
echo $fruits[0]; // apple
echo $fruits[1]; // banana
// Modify elements
$fruits[1] = "grape";
$fruits[] = "kiwi"; // Add to end
// Associative arrays
$person = [
"name" => "John Doe",
"age" => 30,
"email" => "[email protected]",
"city" => "New York"
];
// Access associative elements
echo $person["name"]; // John Doe
echo $person["age"]; // 30
// Add new elements
$person["phone"] = "555-1234";
// Mixed arrays
$users = [
"admin" => ["name" => "Admin", "role" => "superuser"],
"user1" => ["name" => "John", "role" => "editor"],
0 => ["name" => "Jane", "role" => "viewer"]
];
// Array functions
$numbers = [1, 2, 3, 4, 5];
echo count($numbers); // 5
echo array_sum($numbers); // 15
echo array_product($numbers); // 120
echo max($numbers); // 5
echo min($numbers); // 1
echo in_array(3, $numbers); // true (or 1)
echo array_search(3, $numbers); // 2
// Sorting
sort($numbers); // Sort ascending
rsort($numbers); // Sort descending
asort($person); // Sort associative by values
ksort($person); // Sort associative by keys
// Array manipulation
$first = array_shift($numbers); // Remove first element
$last = array_pop($numbers); // Remove last element
array_push($numbers, 6); // Add to end
array_unshift($numbers, 0); // Add to beginning
// Array filtering
$even = array_filter($numbers, function($n) {
return $n % 2 == 0;
});
// Array mapping
$squared = array_map(function($n) {
return $n * $n;
}, $numbers);
// Multidimensional arrays
$matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
echo $matrix[1][2]; // 6
?>
2. Objects
Objects are instances of classes:
<?php
class User {
public $name;
public $email;
private $password;
public function __construct($name, $email, $password) {
$this->name = $name;
$this->email = $email;
$this->password = $password;
}
public function getDisplayName() {
return strtoupper($this->name);
}
}
// Create object
$user = new User("John Doe", "[email protected]", "secret123");
// Access properties
echo $user->name; // John Doe
echo $user->email; // [email protected]
// echo $user->password; // Error: private property
// Call methods
echo $user->getDisplayName(); // JOHN DOE
// Check if property exists
echo property_exists($user, 'name'); // true (or 1)
echo method_exists($user, 'getDisplayName'); // true (or 1)
// Convert object to array
$userArray = (array) $user;
print_r($userArray);
// Convert array to object
$data = ["name" => "Jane", "email" => "[email protected]"];
$obj = (object) $data;
echo $obj->name; // Jane
?>
Special Types
1. NULL
NULL represents a variable with no value:
<?php
$variable = null;
$empty = NULL; // Case insensitive
$uninitialized; // This is null
// Check for null
echo is_null($variable); // true (or 1)
echo is_null($uninitialized); // true (or 1)
// Setting variables to null
$name = "John";
unset($name); // $name is now null
echo isset($name); // false (or empty)
// Null coalescing operator (PHP 7+)
$username = $_GET['username'] ?? 'Guest';
echo $username; // 'Guest' if username is not set or null
?>
2. Resources
Resources represent external resources like database connections or file handles:
<?php
// File resource
$file = fopen("test.txt", "w");
echo get_resource_type($file); // stream
fwrite($file, "Hello World");
fclose($file);
// Database resource (using mysqli)
$connection = mysqli_connect("localhost", "user", "pass", "db");
echo get_resource_type($connection); // mysql link
mysqli_close($connection);
// Check if variable is a resource
echo is_resource($file); // false (after fclose)
?>
Type Juggling and Casting
PHP is loosely typed, meaning it automatically converts types when needed:
Automatic Type Conversion
<?php
// String to number in arithmetic
$result = "5" + 3; // 8 (integer)
$result = "5.5" + 3; // 8.5 (float)
// Number to string in concatenation
$text = "The answer is " . 42; // "The answer is 42"
// Boolean to string
echo true . ""; // "1"
echo false . ""; // "" (empty string)
// Array to string (causes notice)
echo [1, 2, 3]; // "Array" with notice
?>
Explicit Type Casting
<?php
// Casting syntaxes
$int = (int) "123";
$float = (float) "12.34";
$string = (string) 123;
$bool = (bool) 1;
$array = (array) "hello";
$object = (object) ["name" => "John"];
// Alternative casting functions
$int = intval("123");
$float = floatval("12.34");
$bool = boolval(1);
// Casting between types
$number = 42;
$string = (string) $number; // "42"
$backToNumber = (int) $string; // 42
// Array casting
$obj = new stdClass();
$obj->name = "John";
$arr = (array) $obj;
// $arr = ["name" => "John"]
// Object casting
$arr = ["name" => "John", "age" => 30];
$obj = (object) $arr;
// $obj->name = "John", $obj->age = 30
?>
Variable Scope
Scope determines where variables can be accessed:
Global Scope
<?php
$name = "Global Variable";
function showName() {
// Cannot access global $name directly
// echo $name; // Would cause an error
// Need to use global keyword
global $name;
echo $name; // "Global Variable"
// Or use $GLOBALS array
echo $GLOBALS['name']; // "Global Variable"
}
showName();
?>
Local Scope
<?php
function calculate() {
$result = 42; // Local variable
return $result;
}
// echo $result; // Error: $result is not accessible here
echo calculate(); // 42
?>
Static Variables
<?php
function counter() {
static $count = 0; // Preserves value between function calls
$count++;
return $count;
}
echo counter(); // 1
echo counter(); // 2
echo counter(); // 3
?>
Superglobal Variables
PHP provides several superglobal variables that are always accessible:
<?php
// $_GET - URL parameters
echo $_GET['param'] ?? 'Not set';
// $_POST - Form data submitted via POST
echo $_POST['username'] ?? 'Not set';
// $_REQUEST - Contains GET, POST, and COOKIE data
echo $_REQUEST['action'] ?? 'Not set';
// $_SERVER - Server and execution environment
echo $_SERVER['HTTP_HOST']; // e.g., localhost
echo $_SERVER['REQUEST_URI']; // e.g., /index.php
echo $_SERVER['REQUEST_METHOD']; // e.g., GET, POST
// $_FILES - Uploaded files
echo $_FILES['upload']['name'] ?? 'No file uploaded';
// $_COOKIE - Cookies
echo $_COOKIE['session_id'] ?? 'No cookie';
// $_SESSION - Session variables
session_start();
$_SESSION['user_id'] = 123;
// $_ENV - Environment variables
echo $_ENV['PATH'] ?? 'PATH not set';
// $GLOBALS - References all global variables
echo $GLOBALS['name'] ?? 'Global name not set';
?>
Variable Variables
PHP allows you to use variable names dynamically:
<?php
$varName = 'username';
$$varName = 'JohnDoe'; // Creates $username variable
echo $username; // JohnDoe
echo $$varName; // JohnDoe
// Practical example
$config = [
'db_host' => 'localhost',
'db_user' => 'admin',
'db_pass' => 'password'
];
foreach ($config as $key => $value) {
$configName = str_replace('db_', '', $key);
$$configName = $value;
}
echo $host; // localhost
echo $user; // admin
echo $pass; // password
?>
Constants
Constants are like variables but their value cannot be changed:
<?php
// Define constants
define('SITE_NAME', 'My Website');
define('MAX_USERS', 1000);
// Using const keyword (PHP 5.3+)
const API_VERSION = '1.0';
const DEBUG_MODE = true;
// Access constants
echo SITE_NAME; // My Website
echo MAX_USERS; // 1000
// Magic constants
echo __LINE__; // Current line number
echo __FILE__; // Full path and filename
echo __DIR__; // Directory of the file
echo __FUNCTION__; // Function name
echo __CLASS__; // Class name
echo __METHOD__; // Class method name
echo __NAMESPACE__; // Namespace name
// Check if constant is defined
if (defined('SITE_NAME')) {
echo SITE_NAME;
}
// Constants are case-sensitive by default
define('GREETING', 'Hello');
echo GREETING; // Hello
// echo greeting; // Error (undefined constant)
// Case-insensitive constants (not recommended)
define('PI', 3.14159, true);
echo PI; // 3.14159
echo pi; // 3.14159 (works because case-insensitive)
?>
Variable Checking Functions
PHP provides several functions to check variable types and states:
<?php
$var = null;
// Type checking
echo is_null($var); // true (or 1)
echo is_bool(true); // true
echo is_int(42); // true
echo is_float(3.14); // true
echo is_string("hello"); // true
echo is_array([1, 2, 3]); // true
echo is_object(new stdClass()); // true
echo is_resource(fopen("test.txt", "r")); // true
// State checking
echo isset($var); // false (null counts as not set)
echo empty($var); // true
echo isset($_GET['param']) ? $_GET['param'] : 'default';
// Type comparison
$value = "42";
echo gettype($value); // string
var_dump($value); // string(2) "42"
// Strict type checking
if ($value === 42) { // false (string vs int)
echo "Exactly equal";
}
if ($value == 42) { // true (type juggling)
echo "Equal";
}
?>
Best Practices
1. Use Descriptive Variable Names
// Bad
$a = 25;
$n = "John";
// Good
$age = 25;
$name = "John";
$user_age = 25;
$max_login_attempts = 5;2. Initialize Variables
// Bad - could cause notices
function calculateTotal() {
return $total + $tax; // $total and $tax undefined
}
// Good
function calculateTotal($subtotal = 0, $taxRate = 0.1) {
$tax = $subtotal * $taxRate;
return $subtotal + $tax;
}3. Use Type Declarations (PHP 7+)
<?php
declare(strict_types=1); // Strict typing
function addUser(string $name, int $age, bool $active): bool {
// Function implementation
return true;
}
// Type hints for properties (PHP 7.4+)
class User {
public string $name;
public int $age;
public bool $isActive;
}
?>
4. Validate User Input
<?php
// Always validate and sanitize input
function processAge($age) {
// Validate it's a number
if (!is_numeric($age)) {
return false;
}
// Cast to integer
$age = (int) $age;
// Validate range
if ($age < 0 || $age > 150) {
return false;
}
return $age;
}
$userAge = processAge($_POST['age'] ?? 0);
if ($userAge === false) {
echo "Invalid age provided";
}
?>
Related Tutorials: