PHP Changing & Casting Types

Changing Types

There is a settype() Function for Changing or Setting the type of a variable in PHP.

Syntax:

bool settype(mixed $var, string $type);

Possible values for the returned string are: Boolean, integer, double, string, array, object, resource NULL.
Returns TRUE on success or FALSE on failure.

Example:

<?php
    $val1 = "Hi";     //string
    $val2 = true;     //boolean
         settype($val1, "integer");  /*$val1 is now 0   (integer)*/
         settype($val2, "string");   /*$val2 is now "1" (string)*/
    echo gettype($val1)." $val1 <br />";
    echo gettype($val2)." $val2 <br />";
?>

Output:

In above example we set the value of $val1 and $val2 .  
After setting value, we change the type of variable $val1 and $val2 using settype() function.
In last 2 statement we display the type of variable using gettype() function.

Tutorialik.com
integer 0 
string 1

Type Casting

You can pretend that a variable or value is of a different type by using a type cast.
This feature works identically to the way it works in C. You simply put the temporary type in parentheses in front of the variable you want to cast.
For example, you could have declared the two variables from the preceding section using a cast:

    $num1 = 50;
    $num2 = (float) $num1;

The second line means "Take the value stored in $num1, interpret it as a float, and store it in $num2."
The $num2 variable will be of type float.
The cast variable does not change types, so $num1 remains of type integer.

Example:

<?php
    $num1 = 50;             /* $num1 integer */
    $num2 = (float) $num1;  /* $num2 float */
    echo gettype($num1)." $num1 <br />";
    echo gettype($num2)." $num2 <br />";
?>

Output:

Tutorialik.com
integer 50
double 50


Share This Page to Download:

Share to Download

Share This Page on:


Ask Question