prestotron
prestotron

Reputation: 35

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

?>

Upvotes: 2

Views: 9794

Answers (4)

Tristup
Tristup

Reputation: 3663

 echo (float) $celcius;

This will do the work for you.

Upvotes: 1

John Kramlich
John Kramlich

Reputation: 2260

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

Upvotes: 0

Andras
Andras

Reputation: 3055

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.

Upvotes: 1

Rama Bramantara
Rama Bramantara

Reputation: 916

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

Upvotes: 1

Related Questions