PHP - Changing a Variable's Data Type

Introduction

You can use PHP's settype() function to change the type of a variable while preserving the variable's value as much as possible.

Demo

<?php
          $test_var = 8.23;
          echo $test_var . " \n ";         
          settype( $test_var, "string" );
          echo $test_var . " \n ";         
          settype( $test_var, "integer" );
          echo $test_var . " \n ";         
          settype( $test_var, "float" );
          echo $test_var . " \n ";         
          settype( $test_var, "boolean" );
          echo $test_var . " \n ";         
?>//from   w w  w  .  j  a  v  a  2s  .  c o m

Result

Here, the $test_var variable contains 8.23, a floating-point value.

Next, $test_var is converted to a string.

After converting $test_var to an integer type, it contains the value 8; the fractional part of the number has been lost permanently.

PHP converts a non-zero number to the Boolean value true.

Related Topic