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');
?>
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
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;
This will do the work for you.
Related
I am setting a session variable in a php file as:
$_SESSION['PageFrom']="check_login_test.php";
Later on the control is transferred to another php file via a form and post. The relevant code in the 2nd file is:
session_start();
$from=trim($_SESSION['PageFrom']);
pageFrom("check_login_test.php",$from);
die('I came here');
Now pageFrom is a function that should have compared the strings and said so. The original function was simply
function oldPageFrom($page,$from)
{
$page= trim($page);
$from=trim($from);
if (strcmp($page,$from)!==0)
{
echo 'The pages are not same';
}
}
Since it did not work as expected, I tried to debug the same and output as much as I can (This changed the old function, but now reveals some things interesting) . The function is
function pageFrom($page,$from)
{
echo '<br/>$page='.$page;
echo '<br/>$from='.$from;
$m=trim($page);
$n=trim($from);
echo "<br/>TrimmedPage=$m<br/>TrimmedFrom=$n";
$k= strcmp($m,$n);
echo '$k='.$k;
if($k !==0);
{
$i=strlen($from);
$j=strlen($page);
if ($i==$j)
{
echo "<br/>The string lengths are Equal $i=$j";
die('Equal in unequal');
}
else
{
echo "<br/>The string lengths are UnEqual $i<>$j";
die('UnEqual in unequal');
}
}
echo 'Works as expected. They are equal'; die('equal');
}
Strangely I get the following as output:
$page=check_login_test.php
$from=check_login_test.php
TrimmedPage=check_login_test.php
TrimmedFrom=check_login_test.php$k=0
The string lengths are Equal 20=20Equal in unequal
So the questions are:
(1)I have trimmed the strings. They are equal and of the same length. Strcmp returns 0. Then why does it enter the loop if($k !==0) at all? Note: no luck in ($k!=0) too.
You're using the following code:
if($k !==0);
{
The semi-colon (;) terminates the if clause and the subsequent { } block won't have any effect. Remove the ; after if and it will work as it should, i.e. this code below
if($k !==0)
{
I have encountered a very weird and concerning problem in some of my PHP code. A variable that I have returns true in an IF statement when it clearly should return false.
$pr = $_SESSION['fin_print_printer']; //this should equal 0
print $pr; //this returns 0, as it should
if($pr == "L"){
print "local";
} else {
print "serve";
}
print $pr; //this returns 0 again, as it should
This prints "local" in my script (in between the two zeros) and does not print "serve". With over 100,000 lines of code in my project, I've not experienced this issue yet, and now I can't figure out what is going on.
If I do if($pr === "L"), then it works as expected, but the above does not.
PHP is trying to typecast 'L' into an int, which results in 0.
intval('L'); // 0
Change your code into the following so it will take types into account:
if($pr === "L")
{
print "local";
}
else
{
print "serve";
}
Or manually typecast $pr to a string.
// You can also to (string)$pr ("0" instead of 0)
if(strval($pr) == "L")
{
print "local";
}
else
{
print "serve";
}
Maybe if you use typecasting (I did't check it):
if ( (string)$pr == "L" ) {
print "local";
} else {
print "serve";
}
Little known approach: You can also do the casting like
if ("L" == $pr) {
Because with loose comparisons, PHP casts the right value to the left value's type, and as you've already been made aware, while string(1)"L" is casted to int(0), int(0) is casted to string(1)"0".
I have found there to be multiple ways to check whether a function has correctly returned a value to the variable, for example:
Example I
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable)
{
// Do something because $somevariable is definitely not null or empty!
}
Example II
$somevariable = '';
$somevariable = get_somevariable();
if ($somevariable <> '')
{
// Do something because $somevariable is definitely not null or empty!
}
My question: what is the best practice for checking whether a variable is correct or not? Could it be different for different types of objects? For instance, if you are expecting $somevariable to be a number, would checking if it is an empty string help/post issues? What is you were to set $somevariable = 0; as its initial value?
I come from the strongly-typed world of C# so I am still trying to wrap my head around all of this.
William
It depends what you are looking for.
Check that the Variable is set:
if (isset($var))
{
echo "Var is set";
}
Checking for a number:
if (is_int($var))
{
echo "Var is a number";
}
Checking for a string:
if (is_string($var))
{
echo "var is a string";
}
Check if var contains a decimal place:
if (is_float($var))
{
echo "Var is float";
}
if you are wanting to check that the variable is not a certain type, Add: ! an exclamation mark. Example:
if (!isset($var)) // If variable is not set
{
echo "Var Is Not Set";
}
References:
http://www.php.net/manual/en/function.is-int.php
http://www.php.net/manual/en/function.is-string.php
http://www.php.net/manual/en/function.is-float.php
http://www.php.net/manual/en/function.isset.php
There is no definite answer since it depends on what the function is supposed to return, if properly documented.
For example, if the function fails by returning null, you can check using if (!is_null($retval)).
If the function fails by returning FALSE, use if ($retval !== FALSE).
If the function fails by not returning an integer value, if (is_int($retval)).
If the function fails by returning an empty string, you can use if (!empty($retval)).
and so on...
It depends on what your function may return. This kind of goes back to how to best structure functions. You should learn the PHP truth tables once and apply them. All the following things as considered falsey:
'' (empty string)
0
0.0
'0'
null
false
array() (empty array)
Everything else is truthy. If your function returns one of the above as "failed" return code and anything else as success, the most idiomatic check is:
if (!$value)
If the function may return both 0 and false (like strpos does, for example), you need to apply a more rigorous check:
if (strpos('foo', 'bar') !== false)
I'd always go with the shortest, most readable version that is not prone to false positives, which is typically if ($var)/if (!$var).
If you want to check whether is a number or not, you should make use of filter functions.
For example:
if (!filter_var($_GET['num'], FILTER_VALIDATE_INT)){
//not a number
}
Could anyone please explain to me why the following line of code prints out true?
$a = "string";
if(isset($a['error'])) echo true; else echo false;
When I do a function call, I return the expected data if it worked properly, or return array("error" => $error);
Then on receiving the returned data I check if isset($var['error']) and if its not then I know I received some expected data.
I would also appreciate if you could advice me if this a good or bad way of handling data between function calls? And if there is a better "good practice" for this.
Well, this is some of PHP misbehaviors, which luckily has been fixed in some recent version.
You can address a single character in a string using the same square braces used to address an array element.
'error' evaluates to 0 and then you have got $a[0] which is set.
to fix that you have to check if $a is array first
I believe it's a bug and it's fixed in PHP 5.4+: http://codepad.viper-7.com/fz1rnT
looks like isset($str[$key]) in same way as isset($str[intval($key)]), where $str and $key are strings
To handle errors best approach are exceptions:
http://php.net/manual/en/language.exceptions.php
I'm not 100% sure why the behavior is like this, but I do know that PHP allows you to handle strings in a similar way as an array.
$a = "StackOverflow";
echo $a[2]; // a
echo $a[4]; // k
echo $a[6]; // v
echo $a[8]; // r
Now when you pass a string key as an index of the array, PHP will try to parse that string into a numerical value to use as a key.
echo $a['stack']; // S
echo $a['over']; // S
echo $a['flow']; // S
echo $a['0stack']; // S
echo $a['1over']; // t
echo $a['2flow']; // a
echo $a['3flow']; // c
echo $a['4flow']; // k
I have the following code:
if ($currentStage == 7)
{
echo include("include/contentP7.php");
}
The content of "content7.php" exists however it is blank.
But when $currentStage is equal to 7 the page is displayed and a random "1" is outputted although "content7.php" is blank.
I assume it may be to do with returning "True" to the if statement. Why is this and how can I remove this "1".
include returns TRUE upon success, when echoed, it becomes 1.
Omit the echo statement:
if ($currentStage == 7) {
include("include/contentP7.php");
}
Include should be on its own.
include probably returns true(1) when includei successful. Remove the echo to get rid of the 1
if ($currentStage == 7)
{
include("include/contentP7.php");
}
I don't understand what the other parts were intended to do. If you wanted to echo a value from contentP7, place that content into a variable (perhaps a HEREDOC or something). Then include and echo like this:
if ($currentStage == 7)
{
include("include/contentP7.php");
echo $contentP7_variable;
}
The "1" or True value might be returned because you are echoing the returned status of the include() but I am not sure how since php.net's manual explains that it is a language construct. I can't test this right now, unfortunately.