PHP Explicit Type Casting to Integer or String

In PHP, while variable types are often handled automatically, you can explicitly convert a variable to an integer or a string using type casting operators or dedicated built-in functions. This article provides a direct, practical guide on how to perform these explicit conversions using (int), (string), intval(), and strval() with clear code examples.

How to Cast a Variable to an Integer

To explicitly convert a variable to an integer in PHP, you can use either the cast operator (int) or the intval() function.

Method 1: Using the (int) or (integer) Operator

This is the fastest and most common way to cast a variable. You simply place the operator before the variable you want to convert.

$floatValue = 12.67;
$stringValue = "42";

$integer1 = (int)$floatValue;   // Output: 12
$integer2 = (int)$stringValue; // Output: 42

Method 2: Using the intval() Function

The intval() function returns the integer value of a variable. It is highly readable and allows you to optionally specify a base for the conversion (defaults to base 10).

$stringValue = "100";
$integer = intval($stringValue); // Output: 100

How to Cast a Variable to a String

To explicitly convert a variable to a string, you can use either the cast operator (string) or the strval() function.

Method 1: Using the (string) Operator

Placing (string) before a variable converts its value into a string.

$integerValue = 582;
$booleanValue = true;

$string1 = (string)$integerValue; // Output: "582"
$string2 = (string)$booleanValue; // Output: "1" (true converts to "1", false converts to "")

Method 2: Using the strval() Function

The strval() function returns the string value of the passed variable.

$floatValue = 19.99;
$string = strval($floatValue); // Output: "19.99"