Why won't PHP print 0 value?

2019-07-20 14:13发布

I have been making a Fahrenheit to Celsius (and vise versa) calculator. All of it works just great, however when I try to calculate 32 fahrenheit to celsius it's supposed to be 0, but instead displays nothing. I do not understand why it will not echo 0 values.

Here is some code:

<?php
// Celsius and Fahrenheit Converter
// Programmed by Clyde Cammarata

$error = '<font color="red">Error.</font>';

function tempconvert($temptype, $givenvalue){
    if ($temptype == 'fahrenheit') {
        $celsius = 5/9*($givenvalue-32);
        echo $celsius;
     }

    elseif ($temptype == 'celsius') {
        $fahrenheit = $givenvalue*9/5+32;
        echo $fahrenheit;
    }
    else {
        die($error);
        exit();

    }
}

tempconvert('fahrenheit', '50');

?>

标签: php echo
4条回答
欢心
2楼-- · 2019-07-20 14:21

looks like $celcius has value 0 (int type) not "0" (string type), so it wont echoed because php read that as false (0 = false, 1 = true).

try change your code

echo $celcius;

to

echo $celcius."";

or

echo (string) $celcius;

it will convert your variable to string

查看更多
看我几分像从前
3楼-- · 2019-07-20 14:23

die() is equivalent to exit(). Either function with the single parameter as an integer value of 0 indicates to PHP that whatever operation you just did was successful. For your function, if you want the value 0 output, you would want to use echo or print, not die() or exit().

Further, consider updating your function to return the value instead of directly outputting it. It will make your code more reusable.

More info about status codes here:

http://php.net/manual/en/function.exit.php

查看更多
Animai°情兽
4楼-- · 2019-07-20 14:41
 echo (float) $celcius;

This will do the work for you.

查看更多
该账号已被封号
5楼-- · 2019-07-20 14:43

when it printed nothing, could you have had a typo in the temptype 'fahrenheit'?

The code matches temptype, and if it's not F or C it errors out. Except that $error is not declared global $error; which uses a local undefined variable (you must not have notices enabled which would warn you), and undefined prints as the "" empty string.

查看更多
登录 后发表回答