PHP - Changing Type by Casting

Introduction

You can change a variable's value via type casting.

Place the name of the desired data type in parentheses before the variable's name.

The variable itself remains unaffected.

In the following example, a variable's value is cast to various different types at the time that the value is displayed:

Demo

<?php
       $test_var = 8.23;
       echo $test_var;
       echo '\n';
       echo (string) $test_var;
       echo '\n';
       echo (int) $test_var;
       echo '\n';
       echo (float) $test_var;
       echo '\n';
       echo (boolean) $test_var;
?>//w  w w.  j  a  va 2  s.  co m

Result

Note

$test_var 's type isn't changed at any point.

It remains a floating-point variable, containing the value 8.23 , at all times.

All that changes is the type of the data that's passed to the echo statement.

Related Topic