HOME HTML EDITOR C JAVA PHP

PHP Casting

Casting in PHP is the process of converting a value from one data type into another. This is often necessary when you receive data as a string (from a form) but need to perform calculations on it as an integer or float.

1. Casting Keywords

You can cast a variable by using the following keywords before the variable name:

2. Cast to Integer

This converts floats (by removing decimals) or numeric strings into whole numbers.

<?php
  $a = 5.95;
  $b = "25.5";

  $cast_a = (int)$a;
  $cast_b = (int)$b;

  echo $cast_a; // Outputs: 5 (decimal is removed)
  echo $cast_b; // Outputs: 25
?>

3. Cast to String

Converting numbers or booleans into strings is useful for display or concatenation.

<?php
  $x = 100;
  $y = true;

  $cast_x = (string)$x;
  $cast_y = (string)$y;

  var_dump($cast_x); // Outputs: string(3) "100"
  var_dump($cast_y); // Outputs: string(1) "1"
?>

4. Cast to Boolean

Most values cast to true. Values that cast to false include 0, "0", empty strings, and NULL.

<?php
  $x = 0;
  $y = "Hello";

  var_dump((bool)$x); // false
  var_dump((bool)$y); // true
?>
Important: When casting a float to an integer, PHP does not round the number. It simply cuts off everything after the decimal point (truncation).