Thursday 30 May 2013

Type Casting In PHP

Since due to its similarity with languages like C and C++ it has Type Casting similar to C and C++.

General example Type Cast a integer to string is:

<?php
$a=20;
$b=(string)$a;//Type Casting Format
?>

 Similarly we can use (int) or (integer) to type cast to integer, (bool) or (boolean) to type cast to Boolean, (float) or (double) or (real) to cast to float, (array) to cast to array and so on for other data types also.

Thing to note is that variable to string Type Casting can be done also by enclosing it within double quotes. Example :

<?php
$a=20;
$str1="$a"; //first Type Casting method
$str2=(string)$a; //second Type Casting method
echo $str1."<br>".$str2;
?>

Output Of this Type Casting script on browser would be :
gettype()
This simply tells what is the type of the variable we have used.
Example:

<?php
$a=TRUE; //boolean 
$b=12; //Integer
$c="12"; //String
$d=12.64; //float
$e="ok"; //String
echo gettype($a).'<br>'.gettype($b).'<br>'.gettype($c).'<br>'.gettype($d).'<br>'.gettype($e);
?>
 Output would be

is_type(variable)
This function simply returns True(1) or False(0) checking the datatype as per the purposed type.
is_int(variable)
is_float(variable)
is_string(variable)
is_boolean(variable)
being some of the functions to check whether matches given data type
Example:
<?php
$a="12"
echo is_string($a);
?>

Output is 
settype()
The settype() function is used to set the type of a variable.
Syntax :  settype(var_name, var_type)

Parameters:


*Mixed : Mixed indicates that a parameter may accept multiple (but not necessarily all) types.

It returns value True or False on success and failure respectively.Hence it has Boolean type

Example:
<?php
$a=12;
$b="12";
settype($a, "string");
settype($b, "integer");
echo $a.'<br>';
echo $b.'<br>';
echo gettype($a).'<br>';
echo gettype($b);
?>

Output would be 

var_dump()
Provides methods for dumping structured information about a variable.The var_dump function displays structured information about expressions that includes its type and value. Arrays are explored recursively with values indented to show structure.

Example:

<?php
$b = 3.1;
$c = true;
var_dump($b, $c);
?>

Output will be:






No comments:

Post a Comment