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".
Related
I just started with PHP... This works so far:
$value = get_field( "transmissie" );
if( $value ) {
echo $value;
} else {
echo 'empty';
}
The value variable can be "Manual" or "Automatic"
What I'm trying to do is to check if the value is "Manual" and then I want to echo 'Manual', but if the value is 'Automatic' then I want to echo this:
Automatic
Can someone put me in the right direction? :)
Thanks!
In PHP and many other languages, == is used to test whether two values match. So in your case it's a simple usage of that operator to get what you want:
if( $value == "Manual" ) {
echo $value;
} else {
echo 'Automatic';
}
N.B. If you want to be sure that both values are of the exact same data type then you would use === instead. (e.g. "1" == 1 will return true, because it considers that the string "1" is the same as the integer 1, whereas "1" === 1 will return false - it considers they are not the same because they are not the same data type.)
There's more information in the manual here: https://www.php.net/manual/en/language.operators.comparison.php
My PHP function thinks my variable ($type) that I am passing to it is empty, but when I tell the function to return that variable ($ype), it returns exactly what I pasted to it.
function getData($result, $player = 0, $type = 0){
// This is here for me to test the bug and it prints $type ok, how when its == 0 ?
if ($type == 0){ return $type; }
if (!empty($result) AND $type != 0){
return $result[$player]->$type;
}elseif (!empty($result) AND $type == 0){
return $result[$player];
}else{
return FALSE;
}
}
This is how I call that function in the code:
$map_type = getData($replay, 1, "name");
Can there be a problem that the file with functions is included? I think nope, as other files and even functions within that file work ok.
I checked it multiple times and I do not see a typos there and I actually tested it and it worked OK.
Is there some bug with setting variables to 0 when they are not sent to function? Again, I dont think so, as the $player works and similar code works on my other functions too.
A loose-typed comparison such as if ($type == 0){ where $type is a string value can lead to unexpected results.
$type will be cast to a numeric for the comparison according to the rules defined here.
So while a string value like "13 Monkeys" will be loose cast to 13, and "13 Monkeys" == 0 will return a false; but a value without any leading digits such as "name" will be cast to a 0, so "name" == 0 is true.
A useful page detailing all the different type comparisons (both loose and strict comparisons) can be found in the PHP docs
Is there a diference between this comparisons ?
What is the diference between ! and === FALSE ?
if (!class_exists($class)) {
require($class.'.php');
}
if (class_exists($class) === FALSE) {
require($class.'.php');
}
In this case, no.
Some people think it's good programming style to explicitly show that they're comparing to a boolean. Personally... I don't like it, but I guess the more verbose form is more obvious, as the ! operator isnt the mose visible thing when smashed between a parenthesis and other vertically'ish characters.
Yes both are the different things:
php automatically considers 0 as "false" and 1 as "true" so when ever you use function response directly inside the if condition at that this both makes a difference.
consider a function, if executed properly at that it returns int number. it may be 0 too.
But if function did not match requirement at that it is returning false.
So at this time function returning value 0 is success. event though the result is zero. At this if you check this in if condition like
$return = someFunction();
if($return){
//code if ture
}
so if $return is 0 your if code will not be executed even your function execution was correct so in that case you should check like
$return = someFunction();
if($return !== FALSE){
//code if ture
}
=== and !== are used to check the response exactly match return type also.
if('0' === 0)
will return false
but
if('0' == 0)
will return true...
Hope your idea is clear now.
check this out:
if('0' == 0){
echo 'Hi, I will be in screen :)';
}
if('0' === 0){
echo 'I will not be in screen :(';
}
can anyone explain why I can't see what's inside the array? I think it supposed to be able to have multiple numbers (subscriptions) so maybe that's why I'm having trouble? Here's the code.
$num = $_SESSION['subscription_ids'];
if(is_array($num))
{
print_r($num);
}
else
{
echo "not an array";
}
//Thanks DonnieM, yet It's spliting out "Array ( ) " no joke.
What is going on?
Your confusion apparently arises from the output of 1 for is_array.
is_array returns a boolean value (true or false). When outputting boolean values as text, true is represented as 1 and false as nothing (an empty string).
Therefore 1 just means yes, this is an array. It does not tell you how many elements there are in the array.
Is this what you mean ?
php > $a = array();
php > echo is_array($a);
1
php > print_r($a);
/* this is not empty, but an empty array */
Array
(
)
/* as long $a is initiate, it WILL NEVER return NULL */
php > var_dump($a);
array(0) {
}
/* but */
php > $a = array(null);
php > var_dump($a);
array(1) {
[0]=>
NULL
}
Hard to say off hand since I don't know what the value of $_SESSION['subscription_ids'] is. It looks to me that you are using the is_array function incorrectly. It returns a boolean value and you're just assigning it to a variable instead. Here is a link to the documentation:
http://php.net/manual/en/function.is-array.php
I would say structure your code like this:
$num = $_SESSION['subscription_ids'];
if(is_array($num))
{
print_r($num);
}
else
{
echo "not an array";
}
Hope this helps!
I want to check if a query variable exists or not. Then I would do something based on that query value. If it exists and is true, do something. If it doesn't exist or is false, do something else such as show a 404 page.
e.g If the url was domain.com?konami=true
if (condition) {
//something
} else {
//show404
}
OPs question is a bit unclear. If you assume that he wants to check that konami is a $_GET parameter and that it has the value of "true" do:
if (isset($_GET["konami"]) === true && $_GET["konami"] === "true") {
// something
} else {
// show 404
}
The problem with the current accepted answer (by Cameron) is that it's lacking the isset check (which is unforgivable, it is objectively wrong). The problem of the highest voted answer (by Jan Hancic) is that it lacks the === "true" check (which is debatable, it depends on how your interpret the question).
Note that && is a lazy-and, meaning that if the first part is false, the second part will never be evaluated, which prevents the "Undefined index" warning. So the order of the statements is important.
Also note that $a === true is not the same as $a === "true". The first compares a boolean whereas the second compares a string.
If you do weak comparison $a == true you are checking for truthy-ness.
Many values are truthy, like the string "true", the number 1, and the string "foo".
Examples of falsy values are: empty string "", the number 0 and null.
"true" == true; // true
"foo" == true; // true
1 == true; // true
"" == true; // false
0 == true; // false
null == true; // false
"true" === true; // false
"true" === false; // false
There is a little confusion around what value should be tested. Do you want to test the konami parameter for being true in the sense of boolean, i.e. you want to test konami parameter for being truthy, or do you want to test if it has string value equal to "true"? Or do you want to test konami parameter for any value in general?
I guess what is wanted here is to test konami for a given string value, "true" in this case, and for being set at the same time. In this case, this is perfectly enough:
ini_set('error_reporting', E_ALL & ~E_NOTICE);
...
if ($_GET['konami'] == "true")
...
This is enough, because if the $_GET['konami'] is unset, it cannot be equal to any string value except for "". Using === is not neccessary since you know that $_GET['konami'] is string.
Note that I turn off the E_NOTICE which someone may not like - but these type of "notices" are normally fine in many programming languages and you won't miss anything if you disable them. If you don't, you have to make your code unecessarily complex like this:
if (isset($_GET['konami']) && $_GET['konami'] == "true")
Do you really want to complicate your code with this, or rather make it simple and ignore the notices like Undefinex index? It's up to you.
Problems with other answers as you mentioned:
#Jan Hancic answer: it tests for true, not "true".
#Cameron answer: might be simplified and he didn't mention the necessity of disabling E_NOTICE.
#Frits van Campen's answer: too complex to my taste, unnecessary test for === true
Umm this?
if (isset($_GET['konami']) === true) {
// something
} else {
//show 404
}
Easy:
if(isset($_GET['konami']) && $_GET['konami'] != 'false') {
//something
} else {
// 404
}
quick and simple.
$konami = filter_input(INPUT_GET, 'konami', FILTER_VALIDATE_BOOLEAN) or die();
ref:
filter flags
filter_input
You may try this code. In this code checked two conditions by one if condition that is $konami contains value and $konami contains 'true'.
$konami = $_GET['konami'];
if( ($konami) && ($konami == "true")){
/*enter you true statement code */
}else {
/* enter your false statement code */
}
You can do it like this:
$konami = false;
if(isset($_GET['konami'])){
$konami = $_GET['konami'];
}
if($konami == "true"){
echo 'Hello World!';
}
else{
header('HTTP/1.0 404 Not Found');
}
In this case you'll always have $konami defined and - if set - filled with the value of your GET-parameter.
if(!$variable) {
//the variable is null
die("error, $variable is null");
}else{
//the variable is set, your code here.
$db->query("....");
}
This works best:
$konami = $_GET['konami'];
if($konami == "true")
{
echo 'Hello World!';
}
else
{
header('HTTP/1.0 404 Not Found');
}
Easiest and shortest way of doing it:
if($konami != null){ echo $konami; } else { header('HTTP/1.0 404 Not Found'); }