My code looks like this:
$muted = 'true'; //Note this is only for testing
if ($muted == 'false' || $muted == '' || $do_not_text == '' || $do_not_text =='false'){
//do this first thing
}
else{
//do something else
}
I can't get my else to run. What syntax am I messing up?
Related to this, I'm storing a value in my database (that will be what's called to set $muted in my real code) that's either 'true', 'false', or ''. What data type should I be storing these as? Currently, I'm using VARCHAR, but I suspect this is all part of the problem.
$do_not_text == '' evaluates to true. Why? Because $do_not_text is not defined which is a falsy value. You are comparing it to an empty string which also equates to a falsy value. So that comparison is true causing the first if statement to be evaluated as true.
I'm not sure why you're using strings for what should be boolean values.
$muted = true; // no need for quotes
You might also consider using the === operator when comparing boolean values.
if ($muted === false || // etc...
What data type should I be storing these as?
Boolean values in MySQL are typically stored as 1 or 0.
field_name TINYINT(1) UNSIGNED NOT NULL DEFAULT 0
Store them as TINYINT with length of 1 because its only 1 and 0, and 0 as the default value.
Then you can make $muted = boolval($db_muted_val); if you want, or use $db_muted_val as is, because 1 is true and 0 is false.
if ($db_muted_val) {
// do this first thing
} else {
// do something else
}
Related
I have a field in a form for entering the number of masters titles won by a Tennis player. Some players have 0 titles. Even though my validation checks for an empty field I cannot enter 0. What changes do I need to make to allow 0 to be entered?
if (empty($_POST["masters"])) {
$has_errors = true;
$mastersErr = "Enter 0-10";
} else {
$masters = validate_input($_POST["masters"]);
}
use if ($_POST["masters"] === '') { to check for empty string
this is because
empty($variable) returns true if $variable equals false, null, '' (empty string) or 0
you can't use $_POST['masters'] == '' because in PHP statement 0 == '' is true
you have to use === operator
please also mind $_POST['xxx'] === 0 will never work because values in $_POST are strings
Anyway if you want user to put number between 0-10 I would suggest to do this check
if(is_numeric($var) && ($var >= 0) && ($var <= 10) && (intval($var) == $var))
{
// OK
}else
{
// not OK
}
This is because space character will pass $_POST["masters"] === '' check.
In validation you should always create if statements keeping in mind to check "is this value OK", not "is this value bad". For example if you want to validate email you dont' check "is value empty" "is value a number" "is value a float", you check "is value a email"|
is_numeric() is good, because
is_numeric('') is false
is_numeric(' ') is false
is_numeric(0) is true
but beware! because
is_numeric('0.1') is also true...
...so you need another check:
(intval($var) == $var) - this is how you make sure user entered integer (not float) number
PHP Manual:
http://www.php.net/manual/en/language.operators.comparison.php
http://www.php.net/is_numeric
http://www.php.net/intval
Sorry for bad english , used Google.translate
There is a code that returns a value to a int, if set . Otherwise it returns false
if (isset($this->variable))
return intval ($this->variable);
else
return false;
On the receiving side condition
if ($return_value) {
// Here code
}
The problem is that if the returned value is 0, this is false, and the code is executed . But as the value of 0 is also important to me . If returned as a string , it is still treated as false.
define ('false', 'value') does not work.
Introduced his constant for this , but you have to rewrite a bunch of code for additional testing
(if($return_value! == my_false_constant)
That is not quite satisfied.
What options are there to solve this problem ?
if ($return_value !== false) {
}
Using !== (or ===) instead of just != or == also tests the type of the value.
Use strict comparison with ===.
See: http://us3.php.net/manual/en/types.comparisons.php
if(1 === true) //returns FALSE
This will work:
(if($return_value !== false){
// do work
}
Comparisons:
== means same value
=== means same value AND same type
! == means not (same value)
!== means not (same value and same type)
SO:
0 == false //is true
0 === false //is false
Simply ! == does not equal !==, as is not valid PHP code
Possibly a strange one that I hope can be done in one line.
I have to have an IF statement that will checks two things.
The first checks if the variable $loggedInfo['status'] is set and is equal to "client".
The second checks that the variable $loggedInfo['address1'] is set and is blank.
The reason being that when the first variable equals staff then the 'address1' variable doesn't exist.
I did have the following but when I log in as staff it still checks for the address1
if((isset($loggedInfo['status'])=="client")&&(!$loggedInfo['address1'])){
//Do something
}
isset returs true or false. you have to do separate check for the actual value
if(
isset($loggedInfo['status']) && $loggedInfo['status']=="client" &&
isset($loggedInfo['address1']) && trim($loggedInfo['address1']) != ''
)
{
//Do something
}
if((isset($loggedInfo['status']) && $loggedInfo['status']=="client") &&(empty($loggedInfo['address1'])){
//Do something
}
isset() returns TRUE if the given variable is defined in the current scope with a non-null value.
empty() returns TRUE if the given variable is not defined in the current scope, or if it is defined with a value that is considered "empty". These values are:
NULL // NULL value
0 // Integer/float zero
'' // Empty string
'0' // String '0'
FALSE // Boolean FALSE
array() // empty array
Depending PHP version, an object with no properties may also be considered empty.
Well you just can't compare the return value of isset() with the string "client", because it will never equal that. To quote http://php.net/manual/en/function.isset.php its return values are "TRUE if var exists and has value other than NULL, FALSE otherwise".
First check if it is set
if ((isset($loggedInfo['status']) === true) && ($loggedInfo['status'] === "client") && (empty($loggedInfo['address1']) === true)) {
// Do something
}
Key take away from this should be to look up return values for every function you use, like empty(), in the manual http://www.php.net/manual/en/function.empty.php. This will save you a lot of headaches in the future.
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.
}
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.