PHP Variables

Beginner
10 min read
Updated: Nov 2026
3 examples
Types, casting & debugging

Definition and Usage

A PHP variable starts with a dollar sign, such as $price, and can hold a value of any type. PHP is loosely typed: the same variable can hold an integer now and a string later, and PHP converts values on its own when an operation needs a different type. That is convenient, but it also means you need tools to ask what a variable holds, convert it on purpose, and look inside it when something goes wrong.

This page covers those tools in five groups: type tests such as is_int() and is_numeric(), conversions such as intval() and settype(), existence checks with isset(), empty() and unset(), debugging output from var_dump() and print_r(), and storing values as text with serialize() and unserialize().

The Variable Functions index has a guide for each of the 37 functions and language constructs in this area.

Test first, convert second.

Most type bugs come from guessing. Check a value with an is_* function or get_debug_type(), then convert it with an explicit cast, instead of relying on PHP to convert it silently.

Some of these are not functions.

isset(), empty() and unset() are language constructs. They look like functions, but you cannot call them through a variable name or pass them as callbacks. They are listed with the functions because you use them the same way.

PHP Syntax

A quick tour of the calls you will use most. The comment on each line shows what it gives back:

PHP
$value = "42abc";

// Type tests: each returns bool
is_int($value);            // false
is_numeric($value);        // false
is_string($value);         // true

// Casting and converting
intval($value);            // int: 42
floatval("3.5kg");         // float: 3.5
strval(10);                // string: "10"
boolval("0");              // bool: false
settype($value, "integer");// bool: true, $value is now int 42

// Existence (language constructs)
isset($value);             // bool: true when set and not null
empty($value);             // bool: true when unset or falsy
unset($value);             // removes the variable

// Debugging
gettype(1.5);              // string: "double"
get_debug_type(1.5);       // string: "float" (PHP 8.0+)
var_dump($data);           // prints type and value
print_r($data);            // prints a readable form
var_export($data);         // prints valid PHP code

// Storing as text
$text = serialize($data);                                // string
$back = unserialize($text, ['allowed_classes' => false]); // value or false

Type Checks (is_*)

Every is_* function takes one value and returns true or false. They never change the value and never raise a warning, so they are safe on any input:

FunctionTrue forRemember
is_int()Integersis_integer() and is_long() are aliases. The string "5" is not an int
is_float()Floatsis_double() is an alias. 5 is an int, so it gives false; is_real() was removed in PHP 8.0
is_numeric()Ints, floats, and numeric strings"12", "1.5" and "1e3" pass; "", "abc" and "0x1A" do not
is_string()StringsAn empty string is still a string
is_bool()true and false0, 1 and "1" are not booleans
is_array()ArraysAn object that behaves like an array (ArrayAccess) is not an array
is_null()Only nullSame as $value === null
is_object()ObjectsIncludes closures and stdClass
is_scalar()Int, float, string, boolnull, arrays, objects and resources are not scalar
is_iterable()Arrays and Traversable objectsMeans you can use it in foreach
is_countable()Arrays and Countable objectsMeans count() will not fail on it
is_callable()Function names, closures, [$obj, 'method']Checks that the value can be called right now
is_resource()Open resourcesA closed resource gives false, even though it was a resource a moment ago

Casting and Converting

Conversion changes a value from one type to another. Each conversion function has a matching cast: (int), (float), (string) and (bool).

FunctionCastExampleRemember
intval()(int)intval("42abc") gives 42Reads digits until the first bad character; text with no leading number gives 0. A float is cut off, not rounded. A second argument sets the base
floatval()(float)floatval("3.14abc") gives 3.14doubleval() is an alias
strval()(string)strval(true) gives "1"false and null become an empty string. Arrays cannot be converted
boolval()(bool)boolval("0.0") gives trueOnly "", "0", 0, 0.0, null, false and [] are false
settype()Nonesettype($v, "integer")Changes the variable itself and returns true or false, not the new value
A cast never fails, and that is the risk.

intval("abc") quietly returns 0, which looks the same as a real zero. When the input must be a number, test it with is_numeric() first and reject it if the test fails.

isset(), empty() and unset()

These three decide whether a variable exists and whether it holds anything useful. They do not raise a warning for a missing variable or array key, which makes them the right tools for optional input:

ConstructReturnsRemember
isset()true when the variable exists and is not nullWith several arguments it is true only if all are set. An array key with a null value counts as not set; use array_key_exists() for that case
empty()true when the variable is missing or falsy"", 0, 0.0, "0", null, false and [] are empty, so a valid 0 counts as empty
unset()NothingRemoves a variable or an array element. After it, isset() is false
empty("0") is true.

If 0 or "0" is a valid answer, such as a quantity or an age, do not use empty(). Use isset() together with a check on the type or value.

Debugging Output

Four functions print a variable in different ways, and two report its type name:

FunctionWhat you getBest for
var_dump()Type, size and value of everything, nestedFinding type bugs, such as "1" against 1
print_r()Short, readable text; true as the second argument returns itLooking at arrays and objects. It hides types: true prints as 1 and false as nothing
var_export()Valid PHP code; true as the second argument returns itCopying a value into a test or a config file
gettype()Legacy name: integer, double, boolean, NULLCode that must run on old PHP versions
get_debug_type()Modern name: int, float, bool, null, or a class nameError messages and logs on PHP 8.0 and later

For deeper work, debug_zval_dump() adds internal reference counts, get_defined_vars() returns every variable in the current scope as an array, and get_resource_id() and get_resource_type() describe a resource such as an open file.

serialize() and unserialize()

serialize() turns a value, including arrays and objects, into a string that can be stored in a file, a cache or a database. unserialize() turns that string back into the value. The format is specific to PHP, so other languages cannot read it.

Never unserialize data you do not trust.

A crafted string can create objects of any loaded class and run their magic methods, such as __wakeup() and __destruct(). This is called object injection. For data from users, cookies or other servers, use json_encode() and json_decode() instead. When you do call unserialize(), pass ['allowed_classes' => false] so that no objects are built.

Also remember that unserialize() returns false when the string is invalid, but false is also a valid result for the string b:0;. Compare against serialize(false) if you need to tell the two apart.

PHP Examples

Three short scripts that use only fixed values, so the output is the same every time you run them.

Example 1 — Type checks and casting

Test five values with is_int(), is_numeric() and is_scalar(), then convert values with intval(), floatval(), strval(), boolval() and settype().

PHP
<?php
$yn = fn(bool $b): string => $b ? 'yes' : 'no';

$samples = [
    'int 42'      => 42,
    'float 3.5'   => 3.5,
    'string "42"' => "42",
    'null'        => null,
    'array'       => [1, 2],
];

foreach ($samples as $label => $v) {
    echo $label, ': int=', $yn(is_int($v)),
         ', numeric=', $yn(is_numeric($v)),
         ', scalar=', $yn(is_scalar($v)), PHP_EOL;
}
echo 'is_callable("strlen"): ', $yn(is_callable('strlen')), PHP_EOL;

var_dump(intval("42abc"));
var_dump(intval(12.9));
var_dump(intval("101", 2));
var_dump(floatval("3.14abc"));
var_dump(strval(true));
var_dump(boolval("0.0"));

$v = "123abc";
settype($v, "integer");
var_dump($v);
?>
intval() Tutorial

How It Works

  1. The arrow function $yn turns a boolean into yes or no, so each line of output stays short.
  2. The string "42" is numeric but is not an int, which is why is_int() says no while is_numeric() says yes. null and the array are not scalar.
  3. intval("42abc") reads the leading 42 and ignores the rest. intval(12.9) drops the decimals without rounding, giving 12.
  4. intval("101", 2) reads the text as a binary number, and 101 in binary is 5.
  5. boolval("0.0") is true, because only the exact string "0" is falsy, not "0.0".
  6. settype() changes $v itself from "123abc" to the integer 123, so var_dump($v) shows int(123).

Example 2 — isset(), empty() and unset()

See how a missing variable, a null, a zero and an empty array each behave with the three constructs.

PHP
<?php
$yn = fn(bool $b): string => $b ? 'true' : 'false';

$name    = 'Ada';
$nothing = null;
$list    = ['a' => 1, 'b' => null];

echo 'isset($name): ', $yn(isset($name)), PHP_EOL;
echo 'isset($nothing): ', $yn(isset($nothing)), PHP_EOL;
echo 'isset($missing): ', $yn(isset($missing)), PHP_EOL;
echo 'isset($list["a"], $list["b"]): ', $yn(isset($list['a'], $list['b'])), PHP_EOL;
echo 'array_key_exists("b", $list): ', $yn(array_key_exists('b', $list)), PHP_EOL;

echo 'empty(0): ', $yn(empty(0)), PHP_EOL;
echo 'empty("0"): ', $yn(empty("0")), PHP_EOL;
echo 'empty("0.0"): ', $yn(empty("0.0")), PHP_EOL;
echo 'empty([]): ', $yn(empty([])), PHP_EOL;

unset($name);
echo 'after unset, isset($name): ', $yn(isset($name)), PHP_EOL;
?>
isset() Tutorial

How It Works

  1. isset($nothing) is false because the value is null, even though the variable was assigned. isset($missing) is also false, and it raises no warning.
  2. With two arguments, isset() needs both to be set. The key 'b' holds null, so the whole call is false.
  3. array_key_exists() only asks whether the key is present, so it returns true for 'b' even though its value is null.
  4. empty() is true for 0, "0" and [], but false for "0.0", because that string is not on the falsy list.
  5. unset($name) removes the variable, so the next isset() call returns false.

Example 3 — Debugging output and serialize()

Print the same array with var_dump(), print_r() and var_export(), compare the type names, and store the array as text and read it back safely.

PHP
<?php
$data = ['id' => 7, 'ok' => true, 'ratio' => 1.5];

var_dump($data);
print_r($data);
echo PHP_EOL;
var_export($data);
echo PHP_EOL;

foreach ([1.5, null, new stdClass(), [1]] as $v) {
    echo gettype($v), ' / ', get_debug_type($v), PHP_EOL;
}

$text = serialize($data);
echo $text, PHP_EOL;

$back = unserialize($text, ['allowed_classes' => false]);
var_dump($back === $data);
?>

How It Works

  1. var_dump() prints the type of every value: int(7), bool(true), float(1.5). It is the only one of the three that shows the difference between 1 and true.
  2. print_r() prints a shorter view. The boolean true shows as 1, so the type information is lost. The extra echo PHP_EOL leaves a blank line before the next output.
  3. var_export() prints valid PHP code with quoted keys and a trailing comma, so you can paste it straight into a script. It adds no final line break, which is why the script prints PHP_EOL itself.
  4. gettype() gives the legacy names double and NULL, while get_debug_type() (PHP 8.0 and later) gives float, null, and the class name stdClass.
  5. serialize() writes each part with its type and length: a:3 is an array of 3 items, s:2:"id" is a 2-character string, i:7 an int, b:1 a bool and d:1.5 a float.
  6. unserialize() with allowed_classes set to false builds the array again and never creates objects, which is the safe way to read stored text. The strict === comparison confirms that the copy is identical.

Next: PHP Variable Functions Index

The functions index lists all 37 functions and constructs in five groups. These are the ones most worth reading first:

FunctionWhat it does
intval()Convert a value to an integer, in any base
settype()Change the type of a variable in place
is_numeric()Check whether a value is a number or a numeric string
isset()Check that a variable exists and is not null
empty()Check that a variable is missing or falsy
var_dump()Print the type and value of a variable
get_debug_type()Get the modern type name of a value
unserialize()Rebuild a value from a serialized string

Full list: PHP Variable Functions index (/php/variable/function).

Frequently Asked Questions

isset() is true when a variable exists and is not null. empty() is true when a variable does not exist or holds a falsy value: an empty string, 0, 0.0, the string '0', null, false, or an empty array. A variable set to 0 is therefore set but also empty. Neither one raises a warning for a missing variable, which is why they are safe to use on input that may not exist.
Because its value is null. isset() treats null as not set. If you need to know whether an array key exists even when its value is null, use array_key_exists('key', $array) instead. For a plain variable, a null value and a missing variable look the same to isset().
For one argument they behave the same: both convert a value to an integer and stop at the first character that is not part of a number, so intval('42abc') is 42. The function form has an extra advantage: its second argument is a base, so intval('101', 2) is 5 and intval('1A', 16) is 26. It can also be passed as a callback, for example array_map('intval', $values).
gettype() returns legacy names such as 'integer', 'double', 'boolean' and 'NULL'. get_debug_type() (PHP 8.0 and later) returns the names you write in code: 'int', 'float', 'bool', 'null', and the class name for objects. Use get_debug_type() in error messages and logs, and gettype() only when you must stay compatible with older PHP versions.
No. Unserializing data you do not control can create objects of any loaded class and trigger their magic methods, which is called object injection and has led to real security holes. Use JSON (json_encode() and json_decode()) for data that crosses a trust boundary. If you must call unserialize(), pass ['allowed_classes' => false] or a short list of safe class names, and only for data you created yourself.
Use var_dump() when the exact type matters, because it prints the type and size of every value. Use print_r() for a short, readable view of arrays and objects. Use var_export() when you want output that is valid PHP code. Both print_r() and var_export() accept true as a second argument to return the text instead of printing it.

Browse every Variable function

Open the functions index for type, cast, existence, debug and serialize guides with examples and FAQs.

Variable Functions Index →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

8 people found this page helpful