PHP MYSQL learners


Type Casting in PHP

PHP Data types are
1. Boolean
2. Integer
3. Float
4. String
5. Array

Converting to Boolean Data type:
Boolean values are true (1) , False (0).
Converting explicitly to Boolean you need to use the bool / boolean casts operator.

Example:
$a = 2; //Integer variable
$b = 2.2 ; //float variable
$c = “hello WORLD”; //string variable
$d = “”;
$ary1 = array();
$ary2 = array(‘aaa’=>’aaa’);echo (bool)$a; {output: 1}
echo (bool)$b; {output: 1}
echo (boolean)$c; {output: 1}
echo (boolean)$d; {output: 0}
echo (bool)$ary1; {output: 0}
echo (bool)$ary2; {output: 1}

Converting to Integer Data type:
It is not possible to convert String Data type into Integer data type
You can convert only decimal, octal, hexadecimal and binary numbers by using INT / INTEGER cast operator.

Example:
$a = 1.33;
Echo (int)$a {output: 1}

Converting to Float Data type:
It is not possible to convert String Data type into Integer data type
You can convert only decimal, octal, hexadecimal and binary numbers by using FLOAT/ DOUBLE / REAL cast operator.

Example:
$a = 1;
echo (float)$a {output: 1.00000000}

Display only 2 decimal places:
$a = 1.1234567;
echo number_format((float)$a,2,’.’,’’); {output: 1.12}


Converting to String Data type:
You can convert to String by using STRING cast operator.

But PHP converts automatically to string form float, integer no need to convert explicitly

Example:
$a = 12; //it is integer variable
$b = (string)$a;
echo gettype($b); {output String}
Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s