Monday, March 16, 2009

Datatypes in Php

In Php you don't need to declare datatype of the variable. Based on the variable assignment value php automatically converts it to corresponding datatype. In php there is eight different datatypes.

A)Four Scalar Types:
1)Integer
2)Float/Double
3)String
4)Boolean

B)Two compound Types:
1)Array
2)Object

C)Two special types:
1)Resource
2)Null

The type of variable is decided at runtime by PHP depending on the context in which that variable is used.

  • With var_dump() function you can check the type and value of an expression.

  • With the gettype() function you can also get the type of the variable.

  • With is_{type}() function you can check a certain type. The {type} within brace means that type should be replaced by any data type.
For Integer type checking the function is is_int()
For String type checking the function is is_string()


  • To convert a variable from one type to another either use cast or use the settype() function.
To convert to integer type use the (int) or (integer) casts
To convert to boolean type use the (bool) or (boolean) casts.
To convert to string type use the (string) cast or the strval() function. Though string conversion is done automatically.
A boolean TRUE value is converted to the string "1" and boolean FALSE is converted to "" (the empty string) and vice-versa.

Below is an example:

<html>
<body>
<?php
$btype=FALSE;
$itype=10;
$ftype=100.1;
$stype="This is a String datatype.";
echo gettype($btype);
echo " ". (boolean)($btype); //Note that the display behaviour of boolean type is
either null or 1.
echo "<br />";
echo gettype($itype);
echo " ".$itype;
echo "<br />";
echo gettype($ftype);
echo " ".$ftype;
echo "<br />";
echo gettype($stype);
echo " ". $stype;
echo "<br />";
?>
</body>
</html>

And the output is,

boolean
integer 10
double 100.1
string This is a String datatype.

Note that boolean TRUE or FALSE is treated differently in Php. If you display boolean FALSE expression, NULL will be printed and if you display boolean TRUE expression, 1 will be printed.

Related Documents
Integer and floating point number in Php
Variables in PHP
Magic constants in php
Boolean datatype in Php

No comments:

Post a Comment