PHP Type Casting
Type casting changes a value from one type to another on purpose. A cast is written as a type name in parentheses just before the value.
A float cast to int
<?php
var_dump((int) 12.9);Numeric text cast to int
<?php
var_dump((int) "12.9");Text cast to float
<?php
var_dump((float) "2.5");A number cast to string
<?php
var_dump((string) 42);Example
<?php
$priceA = "10";
$priceB = "2.5";
$total = (int) $priceA + (float) $priceB;
echo $total, "\n";Key points
- A cast produces a value of the chosen type from the value given.
- The (int) cast cuts a fraction away instead of rounding it.
- Text that holds a number casts to that number.
- The (float) cast turns a whole value or numeric text into a float.
- The (string) cast turns a number into text.
- var_dump shows the type a cast produced, so the change is easy to check.
In this example, the two prices arrive as text, the way a form sends values. The casts change "10" to the integer 10 and "2.5" to the float 2.5. The sum is 12.5, and echo prints it.
Note
Casting makes a new value, and the value cast from keeps its old type.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does var_dump((int) 7.8); print?