Go4Expert

Go4Expert (http://www.go4expert.com/)
-   PHP (http://www.go4expert.com/articles/php-tutorials/)
-   -   Typecasting in PHP (http://www.go4expert.com/articles/typecasting-in-php-t1306/)

pradeep 30Aug2006 18:05

Typecasting 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 14Mar2007 16:08

Re: Typecasting in PHP
 
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 14Mar2007 16:17

Re: Typecasting in PHP
 
Well, i tried running the code, it does not give any such error, post the whole code!

gunwant 14Mar2007 19:28

Re: Typecasting in PHP
 
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;


All times are GMT +5.5. The time now is 15:11.