Boolean issues in PHP - php

I have a question regarding bools in php. I have a stored mysql proc that is returning a boolean. When this value is grabbed on the php side it displays the value as being a 0 or 1. This all seems fine to me and I have read in the php manual that php will interpret a 0 or 1 as false or true at compile time but this does not seem to be the case to me. I have gone a step further and casted my returned value with (bool) but this still does not seem to work.
My if statements are not properly firing because of this. Does anyone know what is going on? Thanks for the help.

MySQL does not have a proper BOOL or BOOLEAN data types. They are declared as synonyms for TINYINT(1). Your procedure will return 0 or 1, which being on non-PHP ground will get transformed into a string in PHP land, so in PHP you have the strings '0' and '1'.
It is weird however that boolean casting does not convert them to the appropriate booleans. You may have some other bugs in your code.
Are you trying to cast the direct result from the query? Because that one is probably an array and:
var_dump((bool) array('0')); // true
Maybe this is your problem. Inspect the returned result.

It sounds like the boolean value is being returned as a string.
Try something like this:
$your_bool = $field_value === "0" ? false : true;

Using the script below. (You'll have to add HTML line break tags before the word "Boolean" inside the left quote to make the output look like my sample; when I do, Firefox interprets them, making the format look strange).
You'll see that the second line produces a null value which MySQL sees as something different from 0 or 1; for TINYINT it stores the PHP true value correctly but nothing for the PHP false, since a null value has no meaning for TINYINT.
Line four shows type casting with (int) is a way to insure that both PHP true and false are stored to MySQL TINYINT Boolean fields. Retrieving the resultant integers from MySQL into PHP variables works since integers are implicitly cast when assigned to PHP Boolean variables.
echo "Boolean true=".true;
echo "Boolean false=".false;
echo "Boolean (int)true=".(int)true;
echo "Boolean (int)false=".(int)false;
Here's the output from PHP 5.3.1 for MySQL 5.1.41:
Boolean true=1
Boolean false=
Boolean (int)true=1
Boolean (int)false=0
Oh! And PHP Boolean literals may be all lowercase or uppercase with the same result... try it yourself.

I use a helpful function "to_bool" for anything I'm not sure of the type of:
function to_bool($value, $default = false)
{
if (is_bool($value)) {
return $value;
}
if (!is_scalar($value)) {
return $default;
}
$value = strtolower($value);
if (strpos(";1;t;y;yes;on;enabled;true;", ";$value;") !== false) {
return true;
}
if (strpos(";0;f;n;no;off;disabled;false;null;;", ";$value;") !== false) {
return false;
}
return $default;
}
Then:
if (to_bool($row['result'])) { ... }

Related

in_array not working properly in Laravel 5

in_array function is returning 1 if values exists, otherwise it returns an empty string. I am expecting it to return true or false.
Can someone please help me with this?
In PHP the integer value 1 is converted to true, check out the documentation on booleans in PHP here.
You could use it as a boolean like so
$arrBoolean = in_array("needle", $arr);
if ($arrBoolean) {
// Code
}
If you want it to say true or false you could do this
$arrBoolean = in_array("needle", $arr) ? 'True' : 'False';
echo($arrBoolean);
However, if you do that, then they are String representations of a boolean and do not actually work as a boolean, they will be just Strings.

returning true outputs 1 but returning false outputs nothing

It's not very important but I was just curious to know the difference.
echo isA("A"); //outputs 1
echo isA("B"); //outputs nothing. why doesn't it output 0?
Anybody can shed somelight on this matter? It does seem to me as a double standard when you look at it from the point of view that "true" outputs as "1" but "false"does not output "0".
Again, no big deal but I think there must be a reason for PHP to be designed like that. Knowing that may give some more insight into this beautiful language.
A true value will manifest itself as a visible 1, but a false value won't. So, tell me what's the advantage of this method?
example function I referred above;
function isA($input){
if ( $input == "A" ):
return true;
else:
return false;
endif;
}
A boolean TRUE value is converted to the string "1". Boolean FALSE is
converted to "" (the empty string). This allows conversion back and
forth between boolean and string values.
http://us3.php.net/manual/en/language.types.string.php#language.types.string.casting
If you want to print a boolean for debugging you can use var_dump or print_r.
Because when false is casted to string it becomes '' -- empty string.
To see the difference use var_dump(); instead of echo
var_dump((string) true);
var_dump((string) false);

What is the PHP best practice for using functions that return true or false?

After playing with PHP, I discovered that true is returned as 1 and false as null.
echo (5 == 5) // displays 1
echo (5 == 4) // displays nothing
When writing functions that return true or false, what are the best practices for using them?
For example,
function IsValidInput($input) {
if ($input...) {
return true;
}
else {
return false;
}
}
Is this the best way to use the function?
if (IsValidInput($input)) {
...
}
How would you write the opposite function?
IsBadInput($input) {
return ! IsValidInput($input);
}
When would you use the === operator?
After playing with PHP, I discovered that true is returned as 1 and false as null.
That is not true (no pun intended). PHP, like many other languages, has "truthy" and "falsy" values, which can behave like TRUE or FALSE when compared to other values.
It is so beause PHP uses weak typing (vs. strong typing). It automatically converts different types of values when comparing them, so it can eventually compare two values of the same type. When you echo TRUE; in PHP, echo will always output a string. But you passed it a boolean value, that has to be converted to a string before echo can do its job. So TRUE is automatically converted to the string "1", while FALSE is converted to "".
When would you use the === operator?
This weak, or loose, typing is the reason PHP uses two equality operators, == and ===. You use === when you want to make sure both values you are comparing are not just "equal" (or equivalent), but also of the same type. In practice:
echo 1 == TRUE; // echoes "1", because the number 1 is a truthy value
echo 1 === TRUE; // echoes "", because 1 and TRUE are not the same type (integer and boolean)
When writing functions that return true or false, what are the best practices for using them?
Be precise when you can, returning the actual boolean TRUE or FALSE. Typical cases are functions prefixed by is, like isValidInput. One usually expects such functions to return either TRUE or FALSE.
On the other hand, it's useful to have your function return a "falsy" or "truthy" values in some cases. Take strpos, for example. If it finds the substring in position zero, it returns 0 (int), but if the string is not found, it returns FALSE (bool). So:
$text = "The book is on the table";
echo (strpos($text, "The") == FALSE) ? "Not found" : "Found"; // echoes "Not found"
echo (strpos($text, "The") === FALSE) ? "Not found" : "Found"; // echoes "Found"
function isValidInput($input){
return ($input ...); // if your test returns true/false, just return that result
}
Your last example is missing an argument, otherwise fine:
function isBadInput($input){
return !isValidInput($input);
}
Sure. Unless you need it in a different sort of structure, e.g. a while loop.
You never would. Always invert the normal function directly.
When you need to differentiate false from 0, '', etc.
After playing with PHP, I discovered that true is returned as 1 and false as null.
No.. true and false are returned as boolean true and false. When you echo output it must be cast to a string for display. As per the manual:
A boolean TRUE value is converted to the string "1". Boolean FALSE is converted to "" (the empty string). This allows conversion back and forth between boolean and string value.
As for the rest: that's fine, yes, yes, when you want exact type matches, to avoid type juggling in comparisons, e.g. "1" == true is true but "1" === true is false.
function isValidInput($input) {
return ($input...);
}
if(isValidInput($input))
...
if(!isValidInput($input)) // never rewrite inverse functions
...
if(isValidInput($input) === false) {
// Only run if the function returned a boolean value `false`
// Does the same thing as above, but with strict typing.
}

Is it correct way to return value in PHP

I have very basic question regarding return value of a function, and checking the variable value.
function test($var1, $var2){
if ($var1 == $var2){
$var3 = "abc";
return $var3;
}
return false
}
$value = test($var1, $var2);
if ($value){
echo "Value is".$value; //should output abc.
} else {
echo "Not equal";
}
Is it ok to either return a value or return false? For example I am not returning TRUE, it is ok?
When i call the function, i store the return value in a variable $value. How can i check the function did return the $var3? Which of the if condition should be used?
if (!empty($value)) or if (isset($value)) or if ($value) or if (value != false)
Yes, it is common practice in PHP to return FALSE as an indicator of an error condition. (What constitutes an error is your own decision and depends on what the function is supposed to do.)
However, since PHP automatically casts values to Boolean that are of another type (like the empty string or 0, which evaluate to FALSE as well), you should do an explicit check for FALSE like this:
if ($value !== FALSE) ...
As Felix Kling notes in the comments, this is called "strict comparison" (or "identity comparison"). It checks if a value is identical to FALSE, where as != FALSE, == FALSE and if ($value) only check if a value could be interpreted as FALSE.
I'm not a PHP developer, but I don't think your first approach works.
There are other things than the boolean value false interpreted as false:
When converting to boolean, the following values are considered FALSE:
* the boolean FALSE itself
* the integer 0 (zero)
* the float 0.0 (zero)
* the empty string, and the string "0"
* an array with zero elements
* an object with zero member variables (PHP 4 only)
* the special type NULL (including unset variables)
* SimpleXML objects created from empty tags
http://php.net/manual/en/language.types.boolean.php
It's perfectly OK to return different data types.
If you want to check against false, use: if ($value !== false). If you get lost which condition to use, this will clarify it: http://www.php.net/manual/en/types.comparisons.php
Your function returns false, so I would go with that check: if ($value != false)
$var3 = "abc";
return $var3;
That's pointless. You're returning a value, not a variable. return "abc"; is perfectly fine.
Is it ok to either return a value or return false?
Yes, that's perfectly fine for a simple case such as this.
How can i check the function did return the $var3?
As said above, the function returns the value "abc", not $var3. You're saving it in a new variable $value. This variable is definitely set (you just created it right there), so there's no need for isset or empty. Just test whether its value is true or false (or whatever else you want to test for). So the way you're doing it in fine.
Yes, you can return pretty much anything from the function, or you can just "return" without returning anything. In your example, you'll get a string or "false" in return.
To check for false you either do if (!$variable) or if ($variable===false). Zero will return true if you do "if ($variable==false)" due to auto casting of zero to false (and any other positive number to true). Three "===" makes sure it really is false and nothing else. The isset($var) checks for existance, not value - and is not applicable to your example since your function will return a value or "false" and thus always exists.
The only right answer here is: it depends.
I always ask myself this question when creating a function like this. To answer it, I analyze what the function does, instead of what it returns.
For instance, if I have a getter, I expect to get a value, or nothing. In this case I often return null when nothing is found/something went wrong.
A test function like yours should return a boolean at all times, in my opinion. Returning a variable when you're checking for something to be true or false is semantically incorrect, I think.
Aside from the semantics: returning 0, false or null does not really matter when you're checking it with if (test($var1, $var2)), since it will all work the same. However, if you want some finer details, you want to do an identity check (===) rather than a equality check. In PHP this is sometimes the case, for instance strpos can return 0 or false, 0 being a match is found, and false is not. Therefore the following would fail:
// returns 0, which is casted to false, so the 'else' part is executed
if (strpos('a', 'abc')) {
// 'abc' contains 'a'
} else {
// 'abc' does not contain 'a'
}
So, long story short: it depends...

Boolean value turns numeric in PHP

EDIT: I believe my confusion is probably created by this code at the top of the page in which I'm testing for the value of the option... This creates a shortcut method to refer to the option without using the get_option('option') method...
global $options;
foreach ($options as $value) {
if (get_settings( $value['id'] ) === FALSE) {
$$value['id'] = $value['std'];
} else {
$$value['id'] = get_settings( $value['id'] );
}
}
And so when I set the value of a variable, $myvar, via a checkbox checked in my theme's options panel and click save, then view my options.php in worpdress, the value of the variable is
true
And when I do a lookup on this variable using
if($myvar == "true")
It passes.
However, when I set the value directly via the update_options() method, like so...
$mvar = true;
update_option('myvar', $myvar);
The value changes from true to 1
And when I do the same comparison as before, if($myvar == "true"), it now fails. It is no longer "true".
What am I missing? (1) why is "true" and 1, not evaluating the same and (2) What is the update_option method doing to the value of myvar to change the value from true to 1?
Try
if($myvar == true)
and
$myvar = true;
TRUE and FALSE are PHP's built in boolean variables which are much more universal than a true string.
About the update_option. It might not be that the option is changing it to 1. Instead it might be that the when it is inserting it into the database, it inserts it as the string "true". Then, when it comes back it is converted to the boolean value true, which when printed is 1
Try
if ($myvar)
Don't test whether things "equal" true, they are either true or they aren't.
You should change your first test to if($myvar == true) or simply if ($myvar). PHP has some strange rules for what is "true"; Generally, strings evaulate to true, except the special cases of "0" and an empty string "", which type-cast to false.
In your specific example, if ($myvar == "true"):
If $myvar contains a boolean, the expression will evaluate as (bool) == (bool)"true", or (bool) == true
If $myvar contains an integer, it's cast to a string and compared against the string "true"; so your test is failing, because "1" != "true".
If $myvar is a string, string comparison takes place and suddenly only the literal string "true" will successfully compare.
I would guess 2nd and 3rd cases are in effect: Wordpress is likely setting $myval to the string "true" when the from is posted back, so your test passes. When you manually specify boolean true, Wordpress must be converting it to an integer, and then integer comparison takes place and fails, because the integer 1 will be cast to string "1" when compared against "true".
You are doing a loose comparison between the integer 1 and the string 'true'. For this PHP will translate the string to a number. 'test' as a number is 0:
var_dump((int) 'true'); // int(0)
And since 0 is not equal to 1, the comparison will return false.
Like some other answers already correctly pointed out, you should test against the boolean literal TRUE or true. If one operator in a equality check is a boolean, PHP will convert the other operator to a boolean too, which, for the number 1, will give
var_dump((bool) 1); // boolean(true)
And then your test will pass, because true is equal to true.
Check out the Type Comparison Table to understand how PHP juggles types when testing for equality.
As for what check_update does to your boolean, check out the function description:
(mixed) (required) The NEW value for this option name. This value can be a string, an array, an object or a serialized value.
So, no boolean allowed. I've tried briefly to find out from the sourcecode where the conversion takes place, but since WP is a mess to me, couldn't find it. Like someone else suggested, it probably happens when storing it to the database and then getting it back.
"true" is a string, and all strings evaulates to the boolean 1 (try casting (bool) $string. true on the other hand, without quotes, is a boolean and will evaluate to 1.

Categories