Typecasting in PHP

pradeep's Avatar author of Typecasting in PHP
This is an article on Typecasting in PHP in PHP.
PHP will automatically convert data types as necessary across the board - you need not worry about it happening. If you specifically wish to override PHP's type conversion, you can perform what is called a type cast - you forcibly convert a variable of type A to type B. In PHP, type casting looks like this:

Code: PHP
<?php
    $mystring = "wombat";
    $myinteger = (integer)$mystring
?>

At first, $mystring contains a string. However, we type cast it to be an integer, so PHP will convert it to an integer, and place the result into $myinteger. You can type cast as boolean using (bool), string using (string), and floating-point using (float).

Type casting is most often used to specifically enforce a type in order to provide extra security or just to make sure a set type of data is being used. For example, if your script absolutely requires an integer number, it's a smart move to typecast your variable with (integer) so that PHP will convert any other type to integer or do nothing if the type is already integer. Converting a float to an integer will automatically round the number down, and is actually faster than using the equivalent function.
gunwant's Avatar, Join Date: Mar 2007
Newbie Member
Hi pradeep
i want to typecast a string to inteiger ,
c se this code
$date = new DateTime($jdate);

$startDay =(integer)date("d", strtotime($jdate));


//echo $jdate."*****".$startDay ;

//$date->modify("+1 day");
//echo $date->format("Y-m-d");
if($startDay<15) $Balance=1.5;
else if($startDay>14 && $startDay< 25) $Balance=1;
else if($startDay>24 && $startDay<32) $Balance=0.5;

giving an error on last line, error message is ,
parse error, unexpected '<' in C:\\Program Files\\sugarcrm-4.2.0c\\htdocs\\sugarcrm\\modules\\HR\\submitEmplo yee.php on line 103,

please suggest
pradeep's Avatar, Join Date: Apr 2005
Team Leader
Well, i tried running the code, it does not give any such error, post the whole code!
gunwant's Avatar, Join Date: Mar 2007
Newbie Member
thanks to repluy pradeep
I tried this way
(c the second & third line)
it is working fine
but i wan to know that whay it is not workin with earlier code

$date = new DateTime($jdate);

$temp =date("d", strtotime($jdate));

$startDay=(int)$temp;
//echo $jdate."*****".$startDay ;

//$date->modify("+1 day");
//echo $date->format("Y-m-d");
if($startDay<15) $Balance=1.5;
else if($startDay>14 && $startDay< 25) $Balance=1;
else if($startDay>24 && $startDay<32) $Balance=0.5;