Logical Operator For Or - php

I am trying to do:
if(x != 1 || 2) echo 'okay';
With my code here:
if($_POST["timezone"] != ("Pacific/Midway" || "America/Adak" || "Etc/GMT+10" || "Pacific/Marquesas")) {
$timezone_error = 'Invalid timezone';
}
Whereas I put in information that did not equal, and $timezone_error was still not set, what is the proper OR operator that I should be using, or is this possible at all? I would rather not write $_POST['x'] != 1, $_POST['x'] != 2 all out separately as this is quite a long list.

what you want is something like this
$array = array("Pacific/Midway" , "America/Adak" , "Etc/GMT+10" , "Pacific/Marquesas");
if (!in_array($_POST["timezone"], $array){
$timezone_error = 'Invalid timezone';
}

Correct format would be:
if(x!= 1 || x!=2) echo 'okay';

Related

Add multiple condition in if statement [duplicate]

This question already has answers here:
Checking string length with strlen
(3 answers)
Closed 9 years ago.
I want to add 2 numbers in the strlen command. here is my php code:
$name = mysql_real_escape_string($_POST['dgt']);
if(strlen($name) != "32") {
print "This is not a name.";
} else {
It checks if the length is 32. I want it to check if the length is 32 OR 40. how can I do that?
First of all, don't use mysql_real_escape_string(); the old mysql_ API is deprecated, so consider switching to PDO or mysqli instead.
Second, you should consider using input filtering; $_POST['dgt'] may not exist at all, so use filter_input().
Third, you should use numeric values to compare against the output of strlen(); although PHP will treat "32" as a number, it's better to be explicit.
Lastly, if a name must be either 32 or 40 long, you can simply add the condition:
$name = filter_input(INPUT_POST, 'dgt', FILTER_UNSAFE_RAW);
if (empty($name) || (strlen($name) != 32 && strlen($name) != 40)) {
print "This is not a name.";
}
Alternatively, use in_array():
if (empty($name) || !in_array(strlen($name), array(32, 40))) {
print "This is not a name.";
}
Use the and operator "&&" in your conditional, like the code below.
if(strlen($name) != 32 && strlen($name) != 40)
If you would like it to check if name is length 32 or 40 then use the or operator "||" like the code below.
if(strlen($name) == 32 || strlen($name) == 40)
user2910265 has a good point, assign the return value of strlen() to a variable so that only one call is made, like so.
$length = strlen($name);
if(!($length == 32 || $length == 40))
print "this is not a name.";
} else {
From the PHP: Logical Operators - Manual, you want to use either
or
|| (this form has higher precedence)
$a or $b Or TRUE if either $a or $b is TRUE.
$a || $b Or TRUE if either $a or $b is TRUE.
So, you could use something like this
$len = strlen($name); // just get the length once and then
// use it to compare however many times....
if (!($len == 32 or $len == 40))

greater or = to a post value

Hi all i have a post value which i am checking to see if its been posted it has atleast 4 numbers (digits) this works perfect.
if (isset($_POST['year']) &&
!preg_match('/([0-9]{4})/i', stripslashes(trim($_POST['year']))) ) {
now i want to check that the value is greater or = to a vairable and not sure how to achive what i need
i tried the below with no luck
$yearOff = date("Y")-150;
echo $yearOff;
if (isset($_POST['year']) &&
!preg_match('/([0-9]{4})/i', stripslashes(trim($_POST['year'])))
&& $_POST['year'] > $yearOff ) {
$ageerrors[] = '<span class="error">
You forgot enter your birth YEAR</span>';
}
Rather than an && you need an || OR condition to switch between the three possible invalid states (empty, not 4+ digits, or <= $yearOff:
if (!isset($_POST['year'])
// Lose the stripslashes()...
|| !preg_match('/([0-9]{4})/i',trim($_POST['year']))
|| $_POST['year'] > $yearOff
) {
// Invalid...
}
Note: It isn't clear from your description whether you want the value to be >= $yearOff or you want it to be < $yearOff. In other words, the code above is testing for the invalid state. Use whichever operator is appropriate for the invalid state.
Note 2: To test for at least 4 consecutive digits in the regex, a better pattern is something like:
/\d{4,}/
// If it must be *only* digits and no other characters, anchor with ^$
/^\d{4,}$/
There's no need for the overhead of a () capture group.
$yearOff = date("Y")-150;
echo $yearOff;
$input = #$_POST['year'];
if (!$input || strlen($input) !== 4 || $input < $yearoff) {
### MEEEP, ERROR ###
}
Explanation:
Input is set (not null which would be false), then it must have a string-length of four and finally it's numerical value must be higher or equal $yearOff.
I assigned the value of the input to it's own variable as well, because you only need to take it once out of $_POST.
As all these conditions are negated, I used the or || operator. Naturally the same can be expressed non-negated and with and:
if ($input && strlen($input) === 4 && $input >= $yearoff) {
### THIS IS CALL OKAY ###
}
To better debug this, the next step is to assign the validity to a variable as well:
$inputValid = $input && strlen($input) === 4 && $input >= $yearoff;
if (false === $inputValid) [
### MEEP, ERROR ####
}
Hope this is helpful.

Getting wrong plural from calculation

$n=21;
$p=$n%10==1 && $n%100!=11 ? 0 : $n%10>=2 && $n%10<=4 && ($n%100<10 || $n%100>=20) ? 1 : 2;
why is $p = 2?
it is supposed to be $p = 0!
is it a bug or am I missing something?
I got this from trying to get the plural form for Russian on: http://www.gnu.org/s/hello/manual/gettext/Plural-forms.html
should be this one:
$p=($n%10==1 && $n%100!=11) ? 0 : (($n%10>=2 && $n%10<=4 && ($n%100<10 || $n%100>=20)) ? 1 : 2);
the error was in missing bracets
you can see here: http://php.net/manual/en/language.operators.comparison.php that "It is recommended that you avoid "stacking" ternary expressions. PHP's behaviour when using more than one ternary operator within a single statement is non-obvious". You can see that if you enclose the else part for the first if between ( and ) you will get another result:
$p=$n%10==1 && $n%100!=11 ? 0 : ($n%10>=2 && $n%10<=4 && ($n%100<10 || $n%100>=20) ? 1 : 2);
Maybe you should consider changing you statement to a "regular" if block, something like:
if ($n%10==1 && $n%100!=11)
{
$p =0 ;
}
elseif ($n%10>=2 && $n%10<=4 && ($n%100<10 || $n%100>=20))
{
$p = 1;
}
else
{
$p= 2;
}
this way being easier to read

How to accomplish this if then statement with less repetition?

I have something simple I'm trying to accomplish with less repetition.
By default, I want a div to be shown, however if $x == 1, then check to see if $y != 1, and if $y doesn't, then don't show the block.
However the best I can come up with is the following:
if($x) {
if($y != 1) {
echo '<div>display block</div>';
}
} else {
echo '<div>display block</div>';
}
This seems a bit repetitive.
I know I can tweak it a bit and do something like:
$displayBlock = '<div>display block</div>';
if($x) {
if($y != 1) {
echo $displayBlock;
}
} else {
echo $displayBlock;
}
But even still, I have a feeling that there is a way to do this whole if if else thing which I can't see right now.
How do you accomplish the above with less if statements? So: if $x != 1 (default), then show the displayBlock. if $x == 1, and $y != 1, then show the display block. If $x == 1 && $y == 1, then do not show the displayBlock.
if (!$x || $y != 1) echo $displayBlock;
+1 to zerkms's answer - it's on the money. To help you solve problems like this in the future, it might be handy to look at truth tables Karnaugh maps.
You essentially have two checks:
a) $x (coerced to true or false)
b) $y != 1
$y != 1
T F
$x T 1 0
F 1 1
So, from that you can see that if $x is falsey, or $y != 1 is true, then you should show the display block, hence:
if (!$x || $y != 1) echo $displayBlock;
In order to keep the amount of code down, you could use a more mathematical approach rather than logic; e.g.
<?php
if($x+$y != 2){echo $displayBlock;}
?>
The display box only stays off when the sum of x and y equals 2.
Check these out. http://www.php.net/manual/en/language.operators.logical.php
$displayBlock = '<div>display block</div>';
if((($x) && ($y != 1)) || (!$x)) {
echo $displayBlock;
}
How did we come to this solution?
Look at your statement, and dissect it logically:
If x is true ... and ... y is 1... then print.
Which brings us to:
(($x) && ($y != 1))
See? X is truth AND y is one. That brigns you down to
if (($x) && ($y != 1)) {
//Do that thing
} else {
if (! $x) {
//Do that thing
}
}
Which we can write simply as...
if (($x) && ($y != 1)) {
//Do that thing
} else { if (! $x) {
//Do that thing
}
Okay, so what's this say?
If conditionA do something, or if condition B do something.
Oh, there's an OR.
So, condtion A || condition B
Which of course, brings us back to...
if((($x) && ($y != 1)) || (!$x)) {
I put in more braces than required in there so you can see the flow of things.

PHP if/else errors

In the PHP below if I compare a variable using == it works as I would expect it to, if I use != then my code breaks, can someone explain or help?
$_GET['p'] = 'home';
// DOES NOT work, it will always return "show JS" regardless to what string I have
if ($_GET['p'] != 'home' || $_GET['p'] != 'create.account'){
echo 'show JS';
}else{
echo 'do not show JS';
}
// Works as I would expect it to
if ($_GET['p'] == 'home' || $_GET['p'] == 'create.account'){
echo 'do not show JS';
}else{
echo 'show JS';
}
$_GET['p'] can't be two different things at the same time. You say int the first expression;
p not home or not create.account. Its always true. You should use && instead of ||
You can see the problem by DeMorgans Laws for negation
!( A || B ) === (!A && !B)
The solution you give is impossible because there is no way for both statements to be false, because that would imply the string is equivalent to both the compared strings. The only way the else block would be hit is if both were false (because of the OR statement).
(X != A) || (X != B)
≡ !(X == A) || !(X == B)
≡ !((X == A) && (X == B))
(X == A) && (X == B) is always false since the condition A != B but X cannot be both A and B at the same time. So !((X == A) && (X == B)) and your (X != A) || (X != B) is always true.
if ($_GET['p'] != 'home' && $_GET['p'] != 'create.account')

Categories