TutorialsPHPPHP Data Types
Share:

PHP Data Types

beginner

Part 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
  • Booleanstrue or false

Compound Types

$colors = ["red", "green", "blue"];  // Array
$object = new stdClass();              // Object
$callback = function() { return "hi"; }; // Callable

Arrays can be indexed (numeric keys) or associative (string keys).

Special Types

  • null — represents a variable with no value
  • resource — 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
php

Practical Examples

Example: Working with Different Data Types
php

Exercises

Price Calculator with Type Safety

easy

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)

Mini Quiz

Mini Quiz