PHP Data Types
beginnerPart of PHP Basics
Theory
PHP is a dynamically typed language — variables can hold any type of value, and types are determined at runtime.
Scalar Types
$name = "Alice"; // String
$age = 25; // Integer
$price = 19.99; // Float (double)
$isActive = true; // Boolean- Strings — single (
') or double (") quotes. Double quotes interpolate variables - Integers — whole numbers, can be decimal, hex (
0x), octal (0o), or binary (0b) - Floats — decimal numbers, also called doubles
- Booleans —
trueorfalse
Compound Types
$colors = ["red", "green", "blue"]; // Array
$object = new stdClass(); // Object
$callback = function() { return "hi"; }; // CallableArrays can be indexed (numeric keys) or associative (string keys).
Special Types
null— represents a variable with no valueresource— external resource (file handle, database connection)
Type Juggling
PHP automatically converts types when needed (type juggling):
$result = "5" + 3; // 8 (string "5" converted to int)
$concat = "5" . 3; // "53" (int 3 converted to string)
$sum = "10 apples" + 5; // 15 (PHP takes leading digits)Type Declarations (PHP 7+)
Force strict types with declare(strict_types=1):
Type Declarations Example
phpPractical Examples
Example: Working with Different Data Types
phpExercises
Price Calculator with Type Safety
Write a PHP function with strict types that takes item price (float), quantity (int), and discount percentage (float), and returns the final price (float). Demonstrate type juggling by calling it with a string price.
Expected Output:
Total: $28.35 (3 items at $10.50 each, 10% off)