简体   繁体   中英

Why won't PHP print 0 value?

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');

?>

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.

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

 echo (float) $celcius;

这将为您完成工作。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM