PHP Casting


Casting in PHP is the process of converting a variable from one data type to another. Since PHP is a loosely typed language, it automatically converts variables as needed, but sometimes explicit casting is necessary to ensure correct calculations, comparisons, or function behavior. Understanding casting is crucial for writing accurate and predictable PHP programs.

What is Type Casting?

Type casting allows a programmer to manually convert a variable from one type to another. PHP supports casting to the following types:

  • (int) or (integer) – converts to integer

  • (float), (double), or (real) – converts to floating-point number

  • (string) – converts to string

  • (bool) or (boolean) – converts to boolean

  • (array) – converts to array

  • (object) – converts to object

Casting to Integer

Converting variables to an integer removes decimal points and converts other types to integer values.

<?php
$floatNum = 12.75;
$intNum = (int)$floatNum; // Cast float to integer
echo $intNum . "<br>"; // Outputs: 12

$boolVal = true;
echo (int)$boolVal . "<br>"; // Outputs: 1

$stringNum = "25";
echo (int)$stringNum . "<br>"; // Outputs: 25
?>
  • Floats are truncated, not rounded.

  • Booleans convert to 1 (true) or 0 (false).

  • Numeric strings convert to their numeric value.

Casting to Float / Double

Casting to a float converts values to a decimal number.

<?php
$intNum = 20;
$floatNum = (float)$intNum; // Converts integer to float
echo $floatNum . "<br>"; // Outputs: 20

$stringNum = "15.75";
echo (float)$stringNum . "<br>"; // Outputs: 15.75
?>
  • Integers become floats.

  • Numeric strings with decimal points are converted properly.

Casting to String

You can convert variables to a string to display or manipulate text.

<?php
$intNum = 100;
$floatNum = 12.5;
$boolVal = true;

echo (string)$intNum . "<br>";   // Outputs: "100"
echo (string)$floatNum . "<br>"; // Outputs: "12.5"
echo (string)$boolVal . "<br>";  // Outputs: "1"
?>
  • Booleans convert to "1" for true and "" for false.

  • Arrays cannot be directly cast to string; it will produce "Array".

Casting to Boolean

Casting converts values to true or false based on their content.

<?php
$intZero = 0;
$intNonZero = 5;
$stringEmpty = "";
$stringNonEmpty = "PHP";

echo (bool)$intZero . "<br>";        // Outputs: false
echo (bool)$intNonZero . "<br>";     // Outputs: true
echo (bool)$stringEmpty . "<br>";    // Outputs: false
echo (bool)$stringNonEmpty . "<br>"; // Outputs: true
?>
  • Numbers: 0 → false, any other number → true

  • Strings: empty → false, any content → true

  • Useful for conditional checks in if statements.

Casting to Array

Variables can be cast to arrays. Scalars become single-element arrays.

<?php
$intNum = 25;
$floatNum = 12.5;
$stringVal = "Hello";

$arrayInt = (array)$intNum;
$arrayFloat = (array)$floatNum;
$arrayString = (array)$stringVal;

print_r($arrayInt);
print_r($arrayFloat);
print_r($arrayString);
?>
  • Each value becomes the first element of the array with index 0.

  • Objects can also be cast to arrays, with properties converted to keys.

Casting to Object

You can convert arrays or scalars into objects.

<?php
$array = array("name" => "Vicky", "age" => 25);
$object = (object)$array;
echo $object->name . "<br>"; // Outputs: Vicky
echo $object->age . "<br>";  // Outputs: 25

$intVal = 100;
$objInt = (object)$intVal;
echo $objInt->scalar; // Outputs: 100
?>
  • Objects created from arrays have keys as properties.

  • Scalar values are stored in a property called scalar.

Implicit vs Explicit Casting

  • Implicit casting occurs automatically in PHP when needed:

<?php
$sum = "10" + 5; // PHP automatically converts "10" to integer
echo $sum; // Outputs: 15
?>
  • Explicit casting uses (type) to ensure the correct type:

$sum = (int)"10" + 5; // Explicit cast
  • Explicit casting is more reliable and prevents unexpected behavior.

Common Mistakes and Tips

  • Casting non-numeric strings to integers or floats produces 0:

<?php
$val = "PHP123";
echo (int)$val; // Outputs: 0
?>
  • Arrays cannot be directly cast to string; always use implode() if needed.

  • Boolean values may behave unexpectedly if you rely on numeric comparisons; always check types if needed.

Summary of the Tutorial

  • Casting converts variables between types: integer, float, string, boolean, array, object.

  • Integers truncate floats; numeric strings convert to numbers.

  • Booleans follow rules: 0, "", null → false; others → true.

  • Scalars can be converted to arrays and objects.

  • Use explicit casting to avoid unexpected results.

  • Implicit casting occurs automatically but may cause subtle bugs.

  • Understanding casting ensures accurate calculations, proper comparisons, and predictable behavior in PHP programs.

Mastering casting is essential for type-sensitive operations, mathematical calculations, and data manipulation in PHP.


Practice Questions

  1. Create a PHP script that casts a float $num = 12.75 to an integer and prints the result. Include a comment explaining truncation.

  2. Declare a string $strNum = "25" and cast it to an integer. Print the result with a comment explaining numeric string conversion.

  3. Create a PHP file that casts an integer $intVal = 20 to a float and prints it. Include a comment explaining conversion to decimal.

  4. Write a PHP script that casts a boolean $isTrue = true to an integer and prints the result. Include a comment explaining true → 1.

  5. Cast a boolean $isFalse = false to a string and print it. Include a comment explaining false → empty string.

  6. Create a PHP script that casts a string $name = "Vicky" to an array and prints it using print_r(). Include a comment explaining array conversion.

  7. Write a PHP script that casts an array $arr = ["a" => 1, "b" => 2] to an object and prints the properties. Include a comment explaining object conversion.

  8. Create a PHP script that adds a numeric string "10" to an integer 5 without casting and prints the result. Include a comment explaining implicit casting.

  9. Repeat the above operation but explicitly cast the numeric string to integer before addition. Include a comment explaining explicit casting.

  10. Write a PHP script that casts a non-numeric string $str = "PHP123" to an integer and prints the result. Include a comment explaining why the output is 0.


Go Back Top