I am running into a funny problem with a mischievous "if" condition :
$condition1="53==56";
$condition2="53==57";
$condition3="53==58";
$condition=$condition1."||".$condition2."||".$condition3;
if($condition)
{
echo "blah";
}
else
{
echo "foo";
}
Why does the if condition pass?
Why does php echo "blah"? What do I do to make php evaluate the "if" statement and print "foo"?
The problem here is that you're putting your expressions in strings!
Your $condition1, $condition2, and $condition3 variables contain strings, and not the result of an expression, and the same goes for your $condition variable which will be a string that looks like 53==56||53==57||53==58. When PHP evaluates a string it considers it true if it is not empty and not equal to 0, so your script will output blah.
To fix this you just need to take your expressions out of the strings. It should look like this:
$condition1 = 53 == 56; // false
$condition2 = 53 == 57; // false
$condition3 = 53 == 58; // false
$condition = $condition1 || $condition2 || $condition3; // false || false || false = false
if ($condition) {
echo 'blah';
} else {
echo 'foo'; // This will be output
}
You're evaluating strings as booleans; they'll aways be true (except the strings "" and "0". Get rid of almost all of the quotes in your program.
Those aren't conditions, they're strings.
$condition1=53==56;
$condition2=53==57;
$condition3=53==58;
$condition=$condition1 || $condition2 || $condition3;
if($condition)
{
echo "blah";
}
else
{
echo "foo";
}
Because you're not checking those variables, it's saying if (String) will always return true. (unless "")
You should be doing:
if(53==56 || 53==57 || 53==58)
{
echo "blah";
}
else
{
echo "foo";
}
All $condition* variables will evaluate to true. This is how PHP sees it:
if("53==56" || "53==57" || "53==58")
What you want is this:
$condition1 = 53==56;
$condition2 = 53==57;
$condition3 = 53==58;
It's because you're evaluating a string, and strings other than empty strings evaluate to true.
You are concatting a string together, a non-empty string equals TRUE in php.
Because when the if passes, $condition is a string (a concatenation of) containing the text of your conditions. Try using if(eval($condition)).
String always evaluate to true if its not empty
And btw php make implicit conversion to boolean
Related
I try to do this:
if ($var !== ""){
$message = "whatever";
}
But end up having to do this:
if ($var == ""){
//do nothing
} else {
$message = "whatever";
}
Why does that happen? Shouldn't both of those mean the same thing?
!= and == are opposites (non-strict comparison operators).
!== and === are opposites (strict comparison operators, where the value must match what you are comparing exactly).
If you use != instead of !==, your code should work. But:
You should understand what the actual value of your variable is - it's not an empty string. You can use print_r( $var ); to see it.
It's better to use the strict comparison operators === and !==, because they have well-defined behavior that is easier to remember and debug.
As $var is really string just use:
if ($var){//any non-empty string will work fine as it will be casted to boolean automatically
$message = "whatever";
}
$var could be != '' but not= '' eg .. null
if ($var == ""){
//do nothing
} else {
if (is_null($var) {
$message ='NULL';
} else {
$message = "whatever";
}
}
I'm trying to build up a PHP if statement with or ("||") operators, but it doesn't seem to work.
$country_code = "example_country_code";
if ($country_code != 'example_country_code' || !clientIscrawler()) {
echo 'the script can be executed';
}
else {
echo 'skipping';
}
With the given example, it should be echoed skipping, but it doesn't happen like that. What am I doing wrong?
Perhaps the double negatives are giving you problems. Let's rewrite it to:
!($country_code == 'example_country_code') || !clientIscrawler()
This can be turned into an equivalent condition with &&:
!($country_code == 'example_country_code' && clientIscrawler())
By reversing the if you would get this:
if ($country_code == 'example_country_code' && clientIscrawler()) {
echo 'skipping';
} else {
echo 'the script can be executed';
}
Therefore, in your code, it will only print skipping if clientIscrawler() is truthy.
If you have multiple conditions with the OR operator, in which case you don't want the if statement to evaluate as true, the syntax is:
if(!($something == "something" || $something == 'somethingelse')){
do stuff...
}
Here is an example:
$apples = array (
1 => "Pink Lady",
2 => "Granny Smith",
3 => "Macintosh",
4 => "Breaburn"
);
foreach($apples as $apple){
// You don't want to echo out if the apple name is "Pink Lady" or "Macintosh"
if(!($apple == "Pink Lady" || $apple == "Macintosh")){
echo $apple."<br />";
}
}
// Output is:
Granny Smith
Breaburn
In your given code, it all depends on your function call
!clientIscrawler()
You will be getting the script can be executed output only when your function call returns FALSE. I think it is returning TRUE right now, which is why you are not getting the desired output.
Maybe this can help you:
if ( ($country_code != 'example_country_code') || clientIscrawler() == false) {
Try this way:
if ( ($country_code != 'example_country_code') || !clientIscrawler()) { ...
My code as follows:
if($_POST['user_id'] = ''){
//some statement;
}
In the above if condition I have put only single =. PHP is not showing any error but I am getting a white blank page. Does anyone has any clue?
if($_POST['user_id'] = '') means:
$_POST['user_id'] becomes '' .. if ('') // always false
if($_POST['user_id'] == '') means:
$_POST['user_id'] compares to '' .. if ( comparison)
Not sure if trolling or real question...
you said it yourself, you're using a single =. You need 2 to check for equality.
if($_POST['user_id'] == ''){
//some statement;
}
When you use a single equal sign, you're basically "set $_POST['user_id'] to '', then test if it's true). Since '' evaluates to false, you get nothing.
This:
if($_POST['user_id'] = ''){
Tries to assign an empty string to $_POST['user_id']. This:
if($_POST['user_id'] == ''){
Is a comparison. You should almost always be doing the second one - the first one over-rides the value in $_POST, and returns the value of the assignment.
try it
Use it
$user_id = $_POST['user_id'];
if($user_id == ''){
//some statement;
}
inseted of
if($user_id = ''){
//some statement;
}
Or try another one
$user_id = $_POST['user_id'];
if(isset($user_id) && !empty($user_id)){
//some statement;
}
It's not triggering any error because it is a valid condition.
if($_POST['user_id'] = '')
equals to
$_POST['user_id'] = '';
if($_POST['user_id']){
//Boolean comparison of a string. Empty = false. Not empty = true.
}
An example of use:
function division($var1, $var2){
if($var2 > 0){
return $var1/$var2;
return false;
}
if($result = division(50,2)){
//It returned 25 which is true!
}
if(!$result = division(50,0)){
//Returned FALSE because you can't divide by zero!
}
I've been writing my "If this variable is not empty" statements like so:
if ($var != '') {
// Yup
}
But I've asked if this is correct, it hasn't caused a problem for me. Here is the answer I found online:
if (!($error == NULL)) {
/// Yup
}
This actually looks longer than my approach, but is it better? If so, why?
Rather than:
if (!($error == NULL))
Simply do:
if ($error)
One would think that the first is more clear, but it's actually more misleading. Here's why:
$error = null;
if (!($error == NULL)) {
echo 'not null';
}
This works as expected. However, the next five values will have the same and (to many, unexpected) behavior:
$error = 0;
$error = array();
$error = false;
$error = '';
$error = 0.0;
The second conditional if ($error) makes it more clear that type casting is involved.
If the programmer wanted to require that the value actually be NULL, he should have used a strict comparison, i.e., if ($error !== NULL)
It is good to know exactly what is in your variable, especially if you are checking for uninitialized vs null or na vs true or false vs empty or 0.
Therefore, as mentioned by webbiedave, if checking for null, use
$error !== null
$error === null
is_null($error)
if checking for initilized, as shibly said
isset($var)
if checking for true or false, or 0, or empty string
$var === true
$var === 0
$var === ""
I only use empty for ''s and nulls since string functions tend to be inconsistent. If checking for empty
empty($var)
$var // in a boolean context
// This does the same as above, but is less clear because you are
// casting to false, which has the same values has empty, but perhaps
// may not one day. It is also easier to search for bugs where you
// meant to use ===
$var == false
If semantically uninitialized is the same as one of the values above, then initialize the variable at the beginning to that value.
$var = ''
... //some code
if ($var === '') blah blah.
Why just don't
if (!$var)
There are ways:
<?php
error_reporting(E_ALL);
$foo = NULL;
var_dump(is_null($inexistent), is_null($foo));
?>
Another:
<?php
$var = '';
// This will evaluate to TRUE so the text will be printed.
if (isset($var)) {
echo "This var is set so I will print.";
}
?>
To check if it's empty:
<?php
$var = 0;
// Evaluates to true because $var is empty
if (empty($var)) {
echo '$var is either 0, empty, or not set at all';
}
// Evaluates as true because $var is set
if (isset($var)) {
echo '$var is set even though it is empty';
}
?>
Is there a function to check both
if (isset($var) && $var) ?
The empty() function will do the job.
Use it with the not operator (!) to test "if not empty", i.e.
if(!empty($var)){
}
You may use the ?? operator as such:
if($var ?? false){
...
}
What this does is checks if $var is set and keep it's value. If not, the expression evaluates as the second parameter, in this case false but could be use in other ways like:
// $a is not set
$b = 16;
echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16
More info here:
https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator
there you go. that should do it.
if (isset($var) && $var)
if (! empty($var))
It seems as though #phihag and #steveo225 are correct.
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
No warning is generated if the variable does not exist. That means
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
So, it seems !empty($var) would be the equivalent to isset() && $var == true.
http://us2.php.net/empty
Try the empty function:
http://us2.php.net/empty
isset($a{0})
isset AND len is not 0 seems more reliable to me, if you run the following:
<?php
$a=$_REQUEST['a'];
if (isset($a{0})) { // Returns "It's 0!!" when test.php?a=0
//if (!empty($a)) { // Returns "It's empty!!" when test.php?a=0
echo 'It\'s '.$a;
} else { echo 'It\'s empty'; }
?>
$a = new stdClass;
$a->var_false = false;
$a->var_true = true;
if ($a->notSetVar ?? false) {
echo 'not_set';
}
if ($a->var_true ?? false) {
echo 'var_true';
}
if ($a->var_false ?? false) {
echo 'var_false';
}
This way:
if (($var ?? false) == true) {
}
I am amazed at all these answers. The correct answer is simply 'no, there is no single function for this'.
empty() tests for unset or false. So when you use !empty(), you test for NOT UNSET (set) and NOT FALSE. However, 'not false' is not the same as true. For example, the string 'carrots' is not false:
$var = 'carrots'; if (!empty($var)){print 1;} //prints 1
in fact your current solution also has this type problem
$var = 'carrots'; if (isset($var) && $var){print 1;} //prints 1
as does even this
$var = '1.03'; if (isset($var) && $var == true){print 1;} //prints 1
in fact... if you want to do as you described exactly, you need:
$var = 'carrots'; if (isset($var) && $var === true){print 1;} //Note the 3 Equals //doesn't print 1
I suppose the shortest valid way to test this case is :
if (#$var === true){ print 1;}
But suppressing errors for something like this is pretty awful practice.
Don't know if an exact one already exists, but you could easily write a custom function to handle this.
function isset_and_true($var) {
return (isset($var) && $var == true) ? true : false;
}
if (isset_and_true($a)) {
print "It's set!";
}
Check if the variable is set, and true. Ignore warning message
if(#!empty($foo))