PHP Fundamentals

PHP Variables and Data Types Explained

Learn how to declare PHP variables and work with strings, integers, floats, booleans, arrays, and null values.

PHP Variables and Data Types

Variables store values that a program can use and change. In PHP, a variable name begins with a dollar sign ($), followed by its name. Variable names are case-sensitive.

Declaring Variables

$name = "Alex";
$age = 28;
$is_active = true;

PHP determines a variable's type from the value assigned to it. You do not normally need to declare the type before using a variable, although PHP also supports type declarations for function parameters, return values, and properties.

Common Data Types

String: text, such as "Hello". Integer: whole numbers, such as 42. Float: numbers with a fractional part, such as 19.95. Boolean: either true or false. Array: an ordered map that can hold multiple values. Object: an instance of a class. NULL: represents a variable with no value.

Checking a Type

Use var_dump() while learning or debugging to inspect a value and its type:

$price = 19.95;
var_dump($price);

PHP also provides functions such as is_string(), is_int(), is_float(), and is_array() for checking values.

Useful Practices

Choose descriptive variable names, keep naming consistent, and validate external input before using it. Do not assume that a value received from a form or URL has the type or format your application expects. Convert and validate values deliberately, especially before calculations or database operations.

Conclusion

Understanding variables and data types makes PHP code easier to read and safer to maintain. As your applications grow, combine these basics with function type declarations and clear validation rules.