0
<?php
    $data="98.8degrees"; 
    (double)$data; 
    (int)$data; 
    (string)$data; 
    echo $data; 
?>

I was surprised/confused when the actual output was 98.8 degrees

I thought when $data uses (double), it converts to 98.8. Then when moving to (int), it becomes 98 and forth But I guess my analogy is wrong. Can someone explain to me how the output became like that?

1
  • replace (int)$data with $data = (int)$data and it will become an integer. Otherwise you're just casting type but not assigning that value to $data. Commented Jun 18, 2013 at 2:40

3 Answers 3

1

Doing

(double)$data; 
(int)$data; 
(string)$data; 

just return the double, int and string values but they don't change. To change them, you need to do assign the return values to the actual variable like this:

$data = (double)$data; 
$data = (int)$data; 
$data = (string)$data; 
Sign up to request clarification or add additional context in comments.

1 Comment

@Floris that should be a careless mistake
0

You keep casting it, but turn around and discard the results. The value in $data never changes. Try the settype() function.

Comments

0

What you probably meant to do was:

<?php
    $data="98.8degrees"; 
    $data=(double)$data; 
    $data=(int)$data; 
    echo $data; 
?>

If you don't keep the result of your operations, you won't see the result of your operations...

Oh - and I have no idea what you hoped to achieve with the

(string)$string;

statement, since it's unclear if/how you ever defined $string...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.