Is it possible to have 2 conditions within 1 if statement? - php

I currently have the following line of code
elseif($_POST['aspam'] != 'fire'){
print "Is ice really hotter than fire?";
}
Is there any sort of OR function within PHP? as if to say if...
$_POST['aspam'] != 'fire' OR !='Fire'
OR alternatively make my value not case sensitive?
Hopefully this makes sense...

The || or or (lowercase) operator.
elseif($_POST['aspam'] != 'fire' || $_POST['aspam'] != 'Fire'){
print "Is ice really hotter than fire?";
}

Sure.
$_POST['aspam'] != 'fire' or $_POST['aspam'] !='Fire'
Just remember that each condition is separate. Saying or != 'Fire' doesn't automatically interpret it as or $_POST['aspam'] != 'Fire'.
They're called logical operators.
To compare the lowercase:
strtolower($_POST['aspam'] != 'fire'

You can do two conditions like this:
if($_POST['aspam'] != 'fire' || $_POST['aspam'] != 'Fire')
If I were you in this case, I would do:
if(strtolower($_POST['aspam']) != 'fire')

A PHP OR is created with ||, AND created with &&, etc. So your code example would look like:
if ( ($_POST['aspam'] != 'fire') || ($_POST['aspam'] != 'Fire') )
However in your case it would be better to:
if (strtolower($_POST['aspam']) != 'fire')

There are different logical operators in PHP.
Use for "OR" two pipes: ||
$_POST['aspam'] != 'fire' || !='Fire'
Here's a link with all operators:
http://www.w3schools.com/PHP/php_operators.asp

Yes.
if (first condition || second condition){
your code
}
The OR is represented by 2 pipes - ||
Something more:
You can also have AND:
if(first condition && second condition){
Your code...
}
So and is represented by &&

This is the logical OR
$_POST['aspam'] != 'fire' || !='Fire'
and this is the case-insensitive (ToLower function)
strtolower($_POST['aspam']) != 'fire'

Use strtolower($_POST['aspam'] )!='fire'

If you want to make the checking of your variable case insensitive, you can use below code
if(strtolower($_POST['aspam'])!='fire')
echo "this is matching";

OR alternatively make my value not
case sensitive?
if (strtolower($_POST['aspam']) != 'fire'){
}

Yes, this is possible. Try this:
elseif($_POST['aspam'] != 'fire' || $_POST['aspam'] != 'Fire')

You could use case insensitive string comparison:
if (strcasecmp($_POST['aspam'], 'fire') !== 0) {
print "Is ice really hotter than fire?";
}
Or a list:
if (!in_array($_POST['aspam'], array('Fire','fire')) {
...

The shortest option here would probably be stristr:
if (stristr($_POST["aspam"], "FIRE")) {
It does a case-insensitive search. To make it a fixed-length match you might however need strcasecmp or strncasecmp in your case. (However I find that less readable, and doesn't look necessary in your case.)

Related

How to find if a variable is isset and its value equals somthing?

I know it is already asked few time in this forum but i can't get my answer properly.
I have a variable let it be $val i want to check if it is isset and if it's value is equals to 'something'.
if(isset($val) and $val == "something")
{
Do Something ...
}
else
{
Do Another Thing...
}
Note $val is not array, it is a variable. I got a question like this where $val was array.
Thanks In Advance
just use && logical operators
The standard logical operators and, or, not and xor are supported by PHP. Logical operators first convert their operands to boolean values and then perform the respective comparison.
if(isset($val) && $val == "something"){ }
I tested this one it's also working fine
if(isset($val) and $val == "something"){ }
you have to use && operator
if(isset($val) && $val == "something")
{
Do Something ...
}
else
{
Do Another Thing...
}
for AND vs && you can refer this
'AND' vs '&&' as operator

Double equals and tripple equals in php

I searched on StackOverflow and Google and I can't find the answer to this question:
Should we always use the triple equal in PHP for validation?
For example, I have a variable:
$x = '1';
if($x == 1) // will work
if($x === 1) // will not
Now, my point is if we need to validate numeric fields like:
if(is_numeric($x) && $x == '1') { will be the equivalent to if($x === 1)
Since === also validate the type, will it be better if we always use the ===?
From http://me.veekun.com/blog/2012/04/09/php-a-fractal-of-bad-design/
== is useless.
‣ It’s not transitive. "foo" == TRUE, and "foo" == 0… but, of course,
TRUE != 0.
‣
== converts to numbers when possible, which means it converts to floats when possible. So large hex strings (like, say, password
hashes) may occasionally compare true when they’re not. Even
JavaScript doesn’t do this.
‣ For the same reason, "6" == " 6", "4.2" == "4.20", and "133" ==
"0133". But note that 133 != 0133, because 0133 is octal.
‣
=== compares values and type… except with objects, where
=== is only true if both operands are actually the same object! For objects, == compares both value (of every attribute) and type, which
is what === does for every other type. What.
See http://habnab.it/php-table.html
And http://phpsadness.com/sad/47
And http://developers.slashdot.org/comments.pl?sid=204433&cid=16703529
That being said, when you are absolutely sure type is not an issue when you are creating simple expressions, == works well enough in my experience. Just be vigilant.
It depends entirely on the script you're writing, there's not one correct answer for this. Having said that, there aren't many situations where you don't already know the type of the variable (except perhaps user input).
This is the reason I stick to using == and only use === when there could be more than one type of the variable.
The == is fine most of the time, it wouldn't have been invented if you weren't supposed to use it :)
It depends on what you want to do.
Given that from forms, data comes as strings, == is handy because it can compare, for example, strings that represent numbers with numbers with no additional type casting.
if ($_GET['amount'] == 10) {
//...
}
So no, it's not better to always use ===.
if (is_numeric($x) && $x == '1') { ...
This looks redundant to me. Why do we need to check if $x is_numeric AND the value '1'? We know '1' is numeric so if it is equal to '1' then it must be a number.
You could use === comparison:
If you're fine with interpreting it as a string:
if ($x === '1') { ...
or
If you must interpret the value as an int
if ((int) $x === 1) { ...
or
If you don't care about the actual type:
if ($x == '1') { ...
I would say it is better to always use === and remove one = in cases you can justify.
And yes it's equal, though weird. Better way to write it is if(is_numeric($x) && $x == 1)
if you're expecting that variable that you're passing will (and must) be integer than you should use triple equal, if not than you should avoid that.
Although, if you really want to use === than you should be doing conversion of variables to the type that you want along the way, like on this example:
if ((int) $var === 1)
{
// will return true if the $var is 1
}
If you want such a strong validation, then the answer is: yes, definitely use ===.
The == also does some very weird things, like comparing completely different string as equal, just because they are numerically equivalent. So === will probably be a better tool for you in most situations.

OR in PHP IF Statement

I am having trouble with my IF statement, it is always TRUE although this is incorrect. I'm using an OR operator as there are two possible scenarios I want to capture in the IF statement.
The array string ad_status is "1" but using the below -3 is returned, I'm expecting the IF to be FALSE. If I remove the OR and second statement from the IF, the result of the IF is correct.
What have I done wrong? Thanks.
if(($getadstatus['ad_status'] != "1" || $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
Additional:
What I want to do is exit the function (not seen in full here) if ad_status does not equal 1 or 4. If it equals any other value other than 1 or 4, the IF statement should return TRUE and exit.
ad_status could be any value from 0 to 4.
What you are saying is that any value that is not 1 OR is not 4 should return true.
For '1' you get the statement
if( 1 != 1 || 1 != 4)
which translates to
if( false || true )
which is ofcourse true.
What you need is:
if(!($value == 1 || $value==4))
which is the same as (de Morgan's law)
if($value != 1 && $value != 4)
You check:
ad_status != 1 -> FALSE
ad_status != 4 -> TRUE
if (FALSE OR TRUE) is always TRUE.
To be what you expected, replace OR with AND:
if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
It will always be true as any value can't be both '1' and '4' at the same time.
You should use && operator because use !=. If you want to use || you could write like this:
if (!($getadstatus['ad_status'] == "1" || $getadstatus['ad_status'] == "4"))
You want to use &&
if(($getadstatus['ad_status'] != "1" && $getadstatus['ad_status'] != "4"))
{
return -3;
exit;
}
I personally prefer in_array instead of OR in IF statemements. Eg:
$array = array(1,4);
if (!in_array($getadstatus['ad_status'], $array)) {
// do whatever
}
There are no errors there.
If ad_status == 1 then your second condition will get you into the If
$getadstatus['ad_status'] != "4"
is true therefore you will get return -3;
If i got what you want you should use AND
if ( $a!= 1 AND $a!= 4 )
humm, ok I think I see. I'm attempting to be too clever. I want to use a single IF statement to check for two non related conditions. If ad_status does not equal 1 OR 4, return -3 and exit the function.
Okay, no problem, that can be expressed, just formulate like you write:
$status = $getadstatus['ad_status']; // assign a variable as it makes things easier to read.
if ( !( $status==1 || $status==4 ) )
{
return -3;
}
So the ! (not) should be on the whole OR comparison as you wrote in your sentence. That's probably in code what you had originally in mind. But as the order is important, the other part of your condition needs to be inside brackets to be calculated first, before using the not (!) operator.
Added:
The more sub-conditions are part of a condition or expression, the more complex it gets. But the more often you formulate complex conditions the better you will get with them. To train, you can always split conditions over multiple lines and assign labels (variables) to their part:
$status = $getadstatus['ad_status'];
$statusIs1or4 = $status==1 || $status==4;
$statusIsNot1or4 = !$statusIs1or4;
if ($statusIsNot1or4) return -3;
For production code this might be overuse, but as it's always the authors choice how to write something, you can do whatever the language allows.

What exactly does || mean?

return (empty($neededRole) || strcasecmp($role, 'admin') == 0 || strcasecmp($role, $neededRole) == 0);
What exactly does the || mean in this statement? Can someone put this in english for me.
I promise I've googled this but I guess I don't know what to google for because I can't find anything.
thanks:)
It is the OR logicial operator.
http://www.php.net/manual/en/language.operators.logical.php
Googling symbols is always hard. Don't worry: || means or in the statement. Don't confuse it for Xor which is slightly different:
or or || is meant as A or B or A + B
xor is meant as A or B, not both
References:
Logical operator
This is an OR operator. It is true if any of it's 'parameters' is true.
|| means or.
It's a logical or, so it's true if at least one of the terms is true, false otherwise.

does the condition after && always get evaluated

I have this if statement that tests for the 2 conditions below. The second one is a function goodToGo() so I want to call it unless the first condition is already true
$value = 2239;
if ($value < 2000 && goodToGo($value)){
//do stuff
}
function goodToGo($value){
$ret = //some processing of the value
return $ret;
}
My question is about the 2 if conditions $value < 2000 && goodToGo($value). Do they both get evaluated or does the second one only get evaluated when the first one is true?
In other words, are the following 2 blocks the same?
if($value < 2000 && goodToGo($value)) {
//stuff to do
}
if($value < 2000) {
if (goodToGo($value)){
//stuff to do
}
}
No--the second condition won't always be executed (which makes your examples equivalent).
PHP's &&, ||, and, and or operators are implemented as "short-circuit" operators. As soon as a condition is found that forces the result for the overall conditional, evaluation of subsequent conditions stops.
From http://www.php.net/manual/en/language.operators.logical.php
// --------------------
// foo() will never get called as those operators are short-circuit
$a = (false && foo());
$b = (true || foo());
$c = (false and foo());
$d = (true or foo());
Yes. The two blocks are the same. PHP, like most (but not all) languages, uses short-circuit evaluation for && and ||.
The two blocks ARE same.
PHP logical operators are "lazy", they are evaluated only if they are needed.
The following code prints "Hello, world!":
<?php
$a = 10;
isset($a) || die ("variable \$a does not exist.");
print "Hello, world!"
?>
Other logical operators includes &&, and, or.
<?php
perform_action() or die ('failed to perform the action');
?>
is a popular idiom.
the second condition will only be checked if and only if first one is true, hence both statements are equivalent.
Yes, the 2 code blocks you gave are equivalent. PHP has short-circuiting, so when you use
|| and &&, any statement after the first only gets evaluated when necessary.
Always corelate your technical Language with your own language, Likewise here, If I say you in verbal conversation, its just like :You are asking= "if I am hungry '&&' I am eating Pizza" is similar to "If I am hungry then only i am eating Pizza"?
So here you can see that later phrase says that untill i am not hungry i am not eating pizza, and the former says I am humgry and I am eating pizza.
:-)

Categories