Basic Data Types
PHP handles five fundamental data types that form the building blocks of every application you'll create. Understanding these types isn't just academic knowledge - it directly impacts how your programs behave, especially when PHP's automatic type conversion kicks in.
Modern PHP gives you more control over types than ever before. PHP 8 introduced stricter type handling and better error messages. But the language still performs automatic conversions that can surprise newcomers. Let's explore each data type thoroughly so you can write predictable, reliable code.
Understanding PHP's Type System
PHP uses dynamic typing, meaning variables don't need explicit type declarations. The interpreter determines types based on the values you assign. This flexibility speeds development but can lead to unexpected behavior if you don't understand how types work.
<?php
// PHP determines types automatically
$name = "Sarah"; // string
$age = 28; // integer
$height = 5.6; // float
$isActive = true; // boolean
$data = null; // null
// Check types with var_dump()
var_dump($name);
var_dump($age);
var_dump($height);
var_dump($isActive);
var_dump($data);
?>
The var_dump()
function reveals both the type and value of any variable. You'll use this constantly during development to understand what your variables actually contain.
Strings: Text Data in PHP
Strings represent text data - names, messages, HTML content, or any sequence of characters. PHP offers multiple ways to create strings, each with different capabilities and use cases.
Single vs Double Quotes
Single quotes create literal strings. What you type is exactly what you get. Double quotes enable variable interpolation and escape sequences.
<?php
$username = "Alice";
// Single quotes - literal text
$message1 = 'Hello, $username!';
echo $message1;
echo "<br>";
// Double quotes - variable interpolation
$message2 = "Hello, $username!";
echo $message2;
echo "<br>";
// Escape sequences work in double quotes
$formatted = "Line 1\nLine 2\tTabbed";
echo nl2br($formatted); // nl2br() converts \n to <br> for HTML
?>
Use single quotes for simple text. Use double quotes when you need variable substitution or escape sequences like \n
(newline) or \t
(tab).
String Concatenation
PHP uses the dot operator (.
) to join strings together. This differs from many languages that use the plus operator.
<?php
$firstName = "John";
$lastName = "Smith";
// Concatenation with dot operator
$fullName = $firstName . " " . $lastName;
echo $fullName;
echo "<br>";
// Concatenation assignment operator
$greeting = "Hello, ";
$greeting .= $fullName;
$greeting .= "!";
echo $greeting;
?>
Heredoc and Nowdoc
For longer strings, especially those containing HTML or multiple lines, heredoc and nowdoc syntax proves more readable than concatenation.
<?php
$title = "Welcome Page";
$username = "Sarah";
// Heredoc - supports variable interpolation
$htmlContent = <<<HTML
<!DOCTYPE html>
<html>
<head>
<title>$title</title>
</head>
<body>
<h1>Welcome, $username!</h1>
<p>This is your dashboard.</p>
</body>
</html>
HTML;
echo htmlspecialchars($htmlContent); // htmlspecialchars() makes HTML safe to display
?>
Heredoc starts with <<<IDENTIFIER
and ends with IDENTIFIER;
on its own line. The identifier can be any word you choose - HTML
, SQL
, EMAIL
, etc.
Integers: Whole Numbers
Integers represent whole numbers without decimal points. PHP automatically handles the conversion between different number systems and provides useful functions for integer operations.
<?php
// Different ways to write integers
$decimal = 42;
$binary = 0b101010; // Binary representation of 42
$octal = 0o52; // Octal representation of 42
$hex = 0x2A; // Hexadecimal representation of 42
echo "Decimal: $decimal<br>";
echo "Binary: $binary<br>";
echo "Octal: $octal<br>";
echo "Hex: $hex<br>";
// Integer operations
$a = 15;
$b = 4;
echo "Addition: " . ($a + $b) . "<br>";
echo "Subtraction: " . ($a - $b) . "<br>";
echo "Multiplication: " . ($a * $b) . "<br>";
echo "Division: " . ($a / $b) . "<br>"; // Returns float if not evenly divisible
echo "Integer Division: " . intval($a / $b) . "<br>"; // Convert to integer
echo "Modulo: " . ($a % $b) . "<br>"; // Remainder after division
?>
Notice that division can return a float even when working with integers. Use intval()
or integer casting if you need the result as an integer.
Integer Limits and Overflow
PHP integers have size limits that depend on your system architecture. On 64-bit systems, integers can range from approximately -9 quintillion to +9 quintillion.
<?php
// Check integer limits on your system
echo "Maximum integer: " . PHP_INT_MAX . "<br>";
echo "Minimum integer: " . PHP_INT_MIN . "<br>";
echo "Integer size in bytes: " . PHP_INT_SIZE . "<br>";
// What happens when you exceed the limit?
$largeNumber = PHP_INT_MAX;
$overflow = $largeNumber + 1;
echo "Large number type: " . gettype($largeNumber) . "<br>";
echo "Overflow type: " . gettype($overflow) . "<br>";
echo "Overflow value: " . $overflow . "<br>";
?>
When integers overflow, PHP automatically converts them to floats. This prevents crashes but can introduce floating-point precision issues in calculations.
Floats: Decimal Numbers
Floats (also called doubles) represent numbers with decimal points. They're essential for scientific calculations, financial applications, and any scenario requiring fractional values.
<?php
// Different ways to write floats
$price = 19.99;
$scientific = 1.23e4; // Scientific notation: 1.23 × 10^4 = 12300
$small = 5.67e-3; // 5.67 × 10^-3 = 0.00567
echo "Price: $price<br>";
echo "Scientific: $scientific<br>";
echo "Small: $small<br>";
// Float precision issues
$a = 0.1;
$b = 0.2;
$sum = $a + $b;
echo "0.1 + 0.2 = $sum<br>";
echo "Is 0.1 + 0.2 equal to 0.3? " . (($sum == 0.3) ? "Yes" : "No") . "<br>";
// Proper float comparison
$epsilon = 0.00001;
$isEqual = abs($sum - 0.3) < $epsilon;
echo "Proper comparison: " . ($isEqual ? "Yes" : "No") . "<br>";
?>
Never compare floats for exact equality due to precision limitations. Instead, check if the difference between values falls within an acceptable range (epsilon).
Financial Calculations
For financial applications where precision matters, consider using integers to represent cents rather than floats for dollars.
<?php
// Problematic approach with floats
$priceFloat = 19.99;
$taxFloat = $priceFloat * 0.08;
$totalFloat = $priceFloat + $taxFloat;
echo "Float calculation: $" . number_format($totalFloat, 2) . "<br>";
// Better approach with integers (cents)
$priceCents = 1999; // $19.99 in cents
$taxCents = intval($priceCents * 0.08);
$totalCents = $priceCents + $taxCents;
echo "Integer calculation: $" . number_format($totalCents / 100, 2) . "<br>";
// The BCMath extension provides arbitrary precision arithmetic
// but we'll cover that in advanced topics
?>
Booleans: True or False Values
Booleans represent logical values - either true
or false
. They're fundamental to conditional logic and control flow in your applications.
<?php
// Boolean literals
$isLoggedIn = true;
$hasPermission = false;
echo "Logged in: " . ($isLoggedIn ? "Yes" : "No") . "<br>";
echo "Has permission: " . ($hasPermission ? "Yes" : "No") . "<br>";
// Boolean from comparisons
$age = 25;
$isAdult = $age >= 18;
$isMinor = !$isAdult;
echo "Is adult: " . ($isAdult ? "Yes" : "No") . "<br>";
echo "Is minor: " . ($isMinor ? "Yes" : "No") . "<br>";
// Boolean from functions
$email = "[email protected]";
$isValidEmail = filter_var($email, FILTER_VALIDATE_EMAIL);
echo "Valid email: " . ($isValidEmail ? "Yes" : "No") . "<br>";
?>
Truthy and Falsy Values
PHP converts many values to booleans in conditional contexts. Understanding these conversions prevents common logical errors.
<?php
// Values that evaluate to false (falsy)
$falsy_values = [
false,
0,
0.0,
"",
"0",
null,
[]
];
echo "<h3>Falsy Values:</h3>";
foreach ($falsy_values as $index => $value) {
$type = gettype($value);
$display = var_export($value, true);
$bool_result = $value ? "true" : "false";
echo "Value: $display ($type) → $bool_result<br>";
}
// Everything else is truthy
$truthy_values = [
true,
1,
-1,
0.1,
"false", // String "false" is truthy!
" ", // Space character is truthy
[0] // Array with one element is truthy
];
echo "<h3>Truthy Values:</h3>";
foreach ($truthy_values as $index => $value) {
$type = gettype($value);
$display = var_export($value, true);
$bool_result = $value ? "true" : "false";
echo "Value: $display ($type) → $bool_result<br>";
}
?>
The string "0"
is falsy, but "false"
is truthy. Empty arrays are falsy, but arrays containing elements (even falsy elements) are truthy. These rules matter when working with user input and database results.
Null: The Absence of Value
null
represents the absence of a value. Variables can be explicitly set to null
, or they become null
when unset.
<?php
// Explicit null assignment
$data = null;
// Uninitialized variables (generates warning in modern PHP)
// $uninitialized; // Would be null but generates a warning
// Functions returning null
function getData($id) {
if ($id > 0) {
return "Some data for ID: $id";
}
return null; // Explicit return for clarity
}
$result1 = getData(5);
$result2 = getData(-1);
echo "Result 1: " . ($result1 ?? "No data available") . "<br>";
echo "Result 2: " . ($result2 ?? "No data available") . "<br>";
// Null coalescing operator (??)
$username = $_GET['user'] ?? 'Guest'; // Use 'Guest' if $_GET['user'] is null
echo "Username: $username<br>";
// Null checking
if ($data === null) {
echo "Data is null<br>";
}
if (is_null($data)) {
echo "Data is null (using is_null function)<br>";
}
?>
The null coalescing operator (??
) provides elegant handling of potentially null values. It's cleaner than lengthy isset()
checks and handles the common pattern of providing default values.
Type Juggling: PHP's Automatic Conversions
PHP automatically converts between types in many situations. This flexibility can be helpful but sometimes produces unexpected results. Understanding these conversions helps you write predictable code.
<?php
// String to number conversions
$str1 = "42";
$str2 = "42.5";
$str3 = "42abc";
$str4 = "abc42";
echo "String '42' + 8 = " . ($str1 + 8) . "<br>";
echo "String '42.5' + 8 = " . ($str2 + 8) . "<br>";
echo "String '42abc' + 8 = " . ($str3 + 8) . "<br>";
// Boolean conversions in arithmetic
$true_val = true;
$false_val = false;
echo "true + 5 = " . ($true_val + 5) . "<br>";
echo "false + 5 = " . ($false_val + 5) . "<br>";
// Array to string conversion (generates warning)
$array = [1, 2, 3];
echo "Array in string context: " . $array . "<br>";
?>
PHP converts strings to numbers by reading digits from the beginning. "42abc" becomes 42, but "abc42" becomes 0. true
becomes 1 in arithmetic, false
becomes 0.
Concatenation vs Addition
One of PHP's most confusing aspects involves the difference between concatenation (.
) and addition (+
). The operator determines how PHP handles type conversion.
<?php
$a = "5";
$b = "3";
// Concatenation - treats both as strings
echo "Concatenation: " . ($a . $b) . "<br>";
// Addition - converts to numbers
echo "Addition: " . ($a + $b) . "<br>";
// Mixed types
$c = "10";
$d = 5;
echo "String '10' . integer 5 = " . ($c . $d) . "<br>";
echo "String '10' + integer 5 = " . ($c + $d) . "<br>";
// Be careful with user input!
$userInput1 = "7"; // From form field
$userInput2 = "3"; // From form field
// This might not do what you expect
$result = $userInput1 + $userInput2;
echo "User input addition: $result<br>";
// This definitely won't
$unexpected = $userInput1 . $userInput2;
echo "User input concatenation: $unexpected<br>";
?>
Always be explicit about your intentions. Cast variables to the appropriate type if the automatic conversion might cause problems.
Type Checking and Conversion Functions
PHP provides several functions for checking and converting types explicitly. These functions give you control over type handling instead of relying on automatic conversions.
<?php
$value = "42.7";
// Type checking functions
echo "is_string: " . (is_string($value) ? "Yes" : "No") . "<br>";
echo "is_int: " . (is_int($value) ? "Yes" : "No") . "<br>";
echo "is_float: " . (is_float($value) ? "Yes" : "No") . "<br>";
echo "is_bool: " . (is_bool($value) ? "Yes" : "No") . "<br>";
echo "is_null: " . (is_null($value) ? "Yes" : "No") . "<br>";
echo "is_numeric: " . (is_numeric($value) ? "Yes" : "No") . "<br>";
// Type conversion functions
$intValue = intval($value);
$floatValue = floatval($value);
$stringValue = strval($intValue);
$boolValue = boolval($value);
echo "<br>Original: $value (" . gettype($value) . ")<br>";
echo "As integer: $intValue (" . gettype($intValue) . ")<br>";
echo "As float: $floatValue (" . gettype($floatValue) . ")<br>";
echo "As string: $stringValue (" . gettype($stringValue) . ")<br>";
echo "As boolean: " . ($boolValue ? "true" : "false") . " (" . gettype($boolValue) . ")<br>";
?>
Type Casting
PHP supports C-style type casting for explicit conversions. This syntax is more concise than conversion functions but less readable for beginners.
<?php
$original = "123.45";
// Type casting syntax
$int_cast = (int) $original;
$float_cast = (float) $original;
$string_cast = (string) $int_cast;
$bool_cast = (bool) $original;
$array_cast = (array) $original;
echo "Original: $original<br>";
echo "Integer cast: $int_cast<br>";
echo "Float cast: $float_cast<br>";
echo "String cast: $string_cast<br>";
echo "Boolean cast: " . ($bool_cast ? "true" : "false") . "<br>";
echo "Array cast: ";
var_dump($array_cast);
?>
Type casting truncates rather than rounds. (int) "123.99"
becomes 123
, not 124
. Use round()
if you need mathematical rounding.
Practical Examples and Common Pitfalls
Understanding data types becomes crucial when handling real-world scenarios like form processing, database results, and API responses.
Form Data Processing
All form data arrives as strings, regardless of the HTML input type. You must convert values to appropriate types for calculations or comparisons.
<?php
// Simulating form data (normally from $_POST)
$_POST = [
'age' => '25',
'price' => '19.99',
'quantity' => '3',
'newsletter' => 'on' // Checkbox value
];
// Raw form data is always strings
echo "Raw age: '" . $_POST['age'] . "' (" . gettype($_POST['age']) . ")<br>";
// Convert for calculations
$age = (int) $_POST['age'];
$price = (float) $_POST['price'];
$quantity = (int) $_POST['quantity'];
$newsletter = isset($_POST['newsletter']);
echo "Converted age: $age (" . gettype($age) . ")<br>";
echo "Price × Quantity: $" . number_format($price * $quantity, 2) . "<br>";
echo "Newsletter signup: " . ($newsletter ? "Yes" : "No") . "<br>";
// Age validation
if ($age >= 18) {
echo "User is an adult<br>";
} else {
echo "User is a minor<br>";
}
?>
Database Results
Database extensions typically return all values as strings, even for numeric columns. Convert types as needed for your application logic.
<?php
// Simulating database result
$db_row = [
'id' => '1',
'name' => 'John Doe',
'age' => '28',
'salary' => '75000.50',
'is_active' => '1' // Boolean stored as tinyint
];
// Convert database strings to appropriate types
$user = [
'id' => (int) $db_row['id'],
'name' => $db_row['name'],
'age' => (int) $db_row['age'],
'salary' => (float) $db_row['salary'],
'is_active' => (bool) $db_row['is_active']
];
echo "User ID: {$user['id']} (" . gettype($user['id']) . ")<br>";
echo "Name: {$user['name']}<br>";
echo "Age: {$user['age']} years<br>";
echo "Monthly salary: $" . number_format($user['salary'] / 12, 2) . "<br>";
echo "Status: " . ($user['is_active'] ? "Active" : "Inactive") . "<br>";
?>
JSON API Responses
JSON parsing returns specific types, but you might need to convert them for your application requirements.
<?php
// Simulating JSON API response
$json_response = '{"user_id": 123, "balance": "45.67", "premium": true, "last_login": null}';
$data = json_decode($json_response, true);
echo "Original JSON types:<br>";
foreach ($data as $key => $value) {
$type = gettype($value);
$display = var_export($value, true);
echo "$key: $display ($type)<br>";
}
// Convert for application use
$user_id = (int) $data['user_id']; // Already int, but explicit
$balance = (float) $data['balance']; // String to float
$is_premium = (bool) $data['premium']; // Already bool
$last_login = $data['last_login']; // Keep as null
echo "<br>Converted types:<br>";
echo "User ID: $user_id (" . gettype($user_id) . ")<br>";
echo "Balance: $" . number_format($balance, 2) . "<br>";
echo "Premium: " . ($is_premium ? "Yes" : "No") . "<br>";
echo "Last login: " . ($last_login ?? "Never") . "<br>";
?>
Best Practices for Data Types
Following these practices will save you hours of debugging and make your code more maintainable.
Be Explicit About Types
Don't rely on automatic type conversion when the outcome matters. Cast variables explicitly or use type-checking functions.
// Unclear intention
$result = $userInput + $defaultValue;
// Clear intention
$result = (int) $userInput + (int) $defaultValue;
Validate Input Early
Check and convert types immediately when receiving external data. This prevents type-related errors from propagating through your application.
// Validate and convert form input
$age = isset($_POST['age']) ? (int) $_POST['age'] : 0;
if ($age < 1 || $age > 120) {
// Handle invalid age
}
Use Appropriate Comparison Operators
PHP provides both loose (==
) and strict (===
) comparison operators. Use strict comparisons when type matters.
// Loose comparison - can be surprising
if ($value == 0) { /* Matches 0, "0", false, "", null, [] */ }
// Strict comparison - more predictable
if ($value === 0) { /* Only matches integer 0 */ }
Document Expected Types
Use comments or type declarations to make your intentions clear to other developers (including your future self).
/**
* Calculate total price including tax
* @param float $price Base price
* @param float $taxRate Tax rate (e.g., 0.08 for 8%)
* @return float Total price with tax
*/
function calculateTotal($price, $taxRate) {
return $price * (1 + $taxRate);
}
Looking Ahead
Data types form the foundation for everything you'll build in PHP. In the next lesson, we'll explore variables and constants - how to store, name, and manage these different types of data in your applications.
Understanding types deeply will pay dividends as we progress to more complex topics like arrays, objects, and database integration. The time invested in mastering these fundamentals now will prevent countless debugging sessions later.
Remember that PHP's flexibility with types is both a strength and a potential pitfall. Embrace the convenience while staying vigilant about type-related bugs. Modern PHP provides tools to help you manage types effectively - we'll explore those tools as we continue through the course.
← Previous Lesson: Installing PHP Next Lesson: Variables and Constants →