Home » PHP Type Casting Tutorial

PHP Type Casting Tutorial

Type casting in PHP allows you to convert one data type to another.

While PHP is a loosely typed language and automatically converts data types when needed, explicit type casting is often necessary to ensure proper operations or to meet specific requirements.

This tutorial covers:

1. Basics of Type Casting

Type casting explicitly changes a value from one data type to another. For example, you might want to cast a string containing numbers into an integer for mathematical operations.

Example: Automatic vs Explicit Type Conversion

<?php
$number = "100";
echo gettype($number) . "\n";  // string

$number += 50;                // PHP automatically converts to integer
echo gettype($number) . "\n";  // integer
echo $number . "\n";           // 150
?>

Output:

string
integer
150

2. Type Casting Syntax

Use parentheses with the desired data type before the variable or value to perform explicit type casting.

Supported Types:

  • (int) or (integer)
  • (bool) or (boolean)
  • (float), (double), or (real)
  • (string)
  • (array)
  • (object)
  • (unset) (used to cast a value to NULL)

Example: Basic Type Casting Syntax

<?php
$var = "123.45";

$intVar = (int)$var;         // Cast to integer
$floatVar = (float)$var;     // Cast to float
$stringVar = (string)$var;   // Cast to string

echo $intVar . "\n";         // 123
echo $floatVar . "\n";       // 123.45
echo $stringVar . "\n";      // "123.45"
?>

3. Casting Between Data Types

a. String to Integer

When casting a string to an integer, PHP keeps only the numeric part of the string. If the string starts with non-numeric characters, the result is 0.

<?php
$str1 = "123abc";
$str2 = "abc123";

echo (int)$str1 . "\n";  // 123
echo (int)$str2 . "\n";  // 0
?>

b. Integer to Float

Casting an integer to a float adds decimal precision.

<?php
$int = 42;

$float = (float)$int;
echo $float . "\n";  // 42.0
?>

c. Array to Object

Casting an array to an object converts array keys into object properties.

<?php
$array = ["name" => "John", "age" => 30];

$object = (object)$array;
echo $object->name . "\n";  // John
echo $object->age . "\n";   // 30
?>

d. Object to Array

Casting an object to an array converts its properties into key-value pairs.

<?php
$object = (object)["name" => "Alice", "age" => 25];

$array = (array)$object;
print_r($array);
?>

Output:

Array
(
    [name] => Alice
    [age] => 25
)

e. Boolean Conversion

PHP treats certain values as true or false when cast to a boolean:

  • false: 0, 0.0, “” (empty string), “0”, NULL, [] (empty array)
  • true: All other values
<?php
$values = [0, 1, "", "hello", [], [1, 2, 3]];

foreach ($values as $value) {
    echo (bool)$value ? "true\n" : "false\n";
}
?>

Output:

false
true
false
true
false
true

4. Type Casting with settype()

The settype() function changes the type of a variable in place.

Syntax:

settype($variable, "type");

Example: Using settype()

<?php
$var = "456";

settype($var, "integer");
echo gettype($var) . ": $var\n";  // integer: 456

settype($var, "string");
echo gettype($var) . ": $var\n";  // string: 456
?>

5. Practical Examples

Example 1: Sanitizing User Input

When dealing with user input, ensure that numeric values are properly cast to integers.

<?php
$userInput = "123abc";

$age = (int)$userInput;  // Sanitize input
echo "Age: $age\n";      // Age: 123
?>

Example 2: Array to Object Conversion for API Responses

<?php
$response = ["status" => "success", "data" => ["id" => 101, "name" => "John"]];

$responseObject = (object)$response;
echo $responseObject->status . "\n";  // success
echo $responseObject->data["name"] . "\n";  // John
?>

Example 3: Validating Boolean Input

<?php
$userInput = "yes";

$isValid = (bool)$userInput;
echo $isValid ? "True\n" : "False\n";  // True
?>

Example 4: Type Casting in Arithmetic Operations

<?php
$val1 = "10";
$val2 = 20;

$sum = (int)$val1 + $val2;  // Explicit cast to ensure addition
echo "Sum: $sum\n";         // Sum: 30
?>

Example 5: JSON Data Conversion

<?php
$jsonData = '{"name": "Alice", "age": 25}';

$object = json_decode($jsonData);  // JSON string to object
$array = (array)$object;          // Object to array

echo $object->name . "\n";        // Alice
print_r($array);                  // Array
?>

Output:

Alice
Array
(
    [name] => Alice
    [age] => 25
)

Summary of Type Casting in PHP

Type Description Example
(int) Converts to integer (int)”123″ → 123
(float) Converts to float (float)”3.14″ → 3.14
(string) Converts to string (string)123 → “123”
(array) Converts to array (array)$object
(object) Converts to object (object)$array
(bool) Converts to boolean (bool)”” → false

Key Takeaways

  1. Type casting is essential for data consistency in PHP.
  2. Use explicit type casting or settype() when dealing with dynamic or user-provided data.
  3. PHP automatically converts types in many scenarios, but explicit type casting ensures precision.

You may also like