PHP: using if when the second condition might not be set - php

A pretty simple question, I am wondering how php handles the use of IF and AND.
Say i have the following php code:
if ((pony) && (pony == 2)) {
/* do something */
}
if pony is equal to 0, would the code still check if pony is equal to 2 or would it stop there?

No. The boolean operators exhibit short-circuit behavior. In other words, PHP stops evaluating as soon as it knows the result of the entire expression.
See the PHP docs on Logical Operators.

#Jonathon Reinhart is correct, while at the same time you must recognize that you are NOT required to create variables before use.
With that being said this will work:
if ($pony && $pony == 2) {
/* do something */
}
Although, using strict errors in PHP you would need to ensure that (in your case) the variable pony is defined using isset().
if (isset($pony) && $pony == 2) {
/* do something */
}

First, use $ to define variables..
$pony = 0;
if (($pony) && ($pony == 2)) {
echo "yeah";
}
/* false */
The value will be true, if you change the value of $pony = 2;
Logically, nothing was tested during the first condition, its not even a condition.
if($pony){
}
If you change your condition to... where $pony must be 0 and 2 at the same time is impossible
if (($pony == 0) && ($pony == 2)) {
echo "yeah";
}
If you are trying to check if $pony has a value, see Samuel Cook's answer, isset
if (isset($pony) && $pony == 2) {
/* do something */
}
/* does $pony has a value/initiated AND its value must be 2 */

Related

multiple !isset() with OR conditions in php

if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
echo "No";
}
else{ echo "Yes"; }
When I go to index.php?view_quiz, it should give result as Yes, but it results as No. Why?
My Other Tries:
(!isset($_GET['new_quiz'] || $_GET['view_quiz'] || $_GET['alter_quiz']))
( ! ) Fatal error: Cannot use isset() on the result of an expression
(you can use "null !== expression" instead) in
C:\wamp\www\jainvidhya\subdomains\teacher\quiz.php on line 94
(!isset($_GET['new_quiz'],$_GET['view_quiz'],$_GET['alter_quiz']))
NO
You may find than inverting the logic makes the code easier to read, I also like to have a more positive idea of conditions as it can read easier (rather than several nots means no).
So this says if anyone of the items isset() then the answer is Yes...
if(isset($_GET['new_quiz']) || isset($_GET['view_quiz']) || isset($_GET['alter_quiz'])){
echo "Yes";
}
else{ echo "No"; }
Note that I've changed the Yes and No branches of the if around.
You are probably looking for
if(!isset($_GET['new_quiz']) && !isset($_GET['view_quiz']) && !isset($_GET['alter_quiz'])){
echo "No";
}
else {
echo "Yes";
}
which will print Yes if none of new_quiz, view_quiz and alter_quiz are present in the URL. If this is not your desired outcome, please elaborate on your problem.
#paran you need to set a value for view_quiz=yes for example
if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
echo "No";
}
else{ echo "Yes"; }
and the url
index.php?new_quiz=yes
index.php?view_quiz=yes
index.php?alter_quiz=yes
All Will return true
isset()allows multiple params. If at least 1 param does not exist (or is NULL), isset() returns false. If all params exist, isset() return true.
So try this:
if( !isset( $_GET['new_quiz'], $_GET['view_quiz'], $_GET['alter_quiz']) ) {
First, to answer your question:
When I go to index.php?view_quiz, it should give result as Yes, but it results as No. Why?
This is becaue this
if(!isset($_GET['new_quiz']) || !isset($_GET['view_quiz']) || !isset($_GET['alter_quiz'])){
checks if either one of your parameter is not set, which will always be the case as long as you are not setting all three parameter simultaneously like this:
index.php?alter_quiz&view_quiz&new_quiz
As #nigel-ren stated, you may wan't to change that logic to
if(isset($_GET['new_quiz']) || isset($_GET['view_quiz']) || isset($_GET['alter_quiz'])){
echo 'Yes';
which checks if at least one parameter is set.
If you wan't to check if there is only one of the three parameters set, you would have to work with XOR (which is slightly more complicated)
$a = isset($_GET['new_quiz']);
$b = isset($_GET['view_quiz']);
$c = isset($_GET['alter_quiz']);
if( ($a xor $b xor $c) && !($a && $b && $c) ){
echo 'Yes';
(based on this answer: XOR of three values)
which would return true if one and only one of the three parameters is set.
But - and this is just an assumption, please correct me if I'm wrong - I think what you are trying to achieve are three different pages (one for creating a quiz, one for viewing it and one for editing it). Therefore, you will likely run into a problem with your current setup. For example: What would happen if a user calls the page with multiple parameters, like
index.php?alter_quiz&view_quiz
Would you show both pages? Would you ignore one parameter? I would recommend to work with a single parameter to avoid this problem in the first place. For example site which can take the values alter_quiz, view_quiz or new_quiz. E.g.:
index.php?site=alter_quiz
Then you can work like this:
// check if site is set before getting its value
$site = array_key_exists( 'site', $_GET ) ? $_GET['site'] : NULL;
// if it's not set e.g. index.php without parameters is called
if( is_null($site) ){
// show the start page or something
}else{
$allowed_sites = ['new_quiz', 'view_quiz', 'alter_quiz'];
// never trust user input, check if
// site is an allowed value
if( !in_array($site, $allowed_sites, true) ){
die('404 - This site is no available');
}
// here you can do whatever your site should do
// e.g. include another php script which contains
// your site
include('path/to/your/site-' . $site . '.php');
// or echo yes
echo 'Yes';
}

OR statement returning wrong number

If i put 1 or 2 into this it will return 4. Why is this?I'm more used to python stuff so sorry if this is rather basic.
e = 1;
f=0;
if(e==1){f=1;}
if(e==2){f=2;}
if(e== 3 or 4){f=4;}
echo f;
Try replacing :
if(e== 3 or 4){f=4;}
with
if(e == 3 or e == 4){ f=4; }
The value 4 is considered to be TRUE by the language. In your code, 1 == 3 is FALSE, so the if statement is looking at (FALSE or TRUE) which is equals TRUE, so f is set to 4.
Have a look at this link re: PHP Booleans
For your or statement, this is what you want:
if ( ($e == 3) || ($e == 4) ) {
$f=4;
}
The next statement is always going to be true
if(e== 3 or 4)
If you take a look at booleans, you'll see that pretty much everything is equals to true in php (except for those values stated in that same page). So what you really have is something like this:
if($e==3 or true)
And since anything or true is always true, you get that (weird, but not unexpected) result.
In case you want to check if $e is equals to 3 or 4, do it like so:
if($e==3 || $e==4){
Note that since these are not if..else statements, every condition is being checked. Take a look at the expanded version:
if($e==1){
$f=1;
}
if($e==2){
$f=2;
}
if($e==3 or 4){
$f=4;
}
This /\ is different from
if($e==1){
$f=1;
}elseif($e==2){
$f=2;
}elseif($e==3 or 4){
$f=4;
}
Since the latter only checks every condition in case none of the previous fit.
Another side note.. since you like python, that code could be converted into this single line:
$f = ($e==3 || $e==4) ? 4 : $e;

Understanding php logic on conditionals - return true understanding

The point is to validate, only when,
$this->data[$this->alias]['enabled']
It's equal to one. So, if $this->data[$this->alias]['enabled'] == 1, validate.
I was expecting that this peace of code, would do the job:
public function compareDates() {
if ($this->data[$this->alias]['enabled'] == 1) {
return $this->data[$this->alias]['firstPageEnterDate'] < $this->data[$this->alias]['firstPageLeaveDate'];
}
}
However it seems that that doesn't work as I expected. Instead, it gets always validated, regardless the value of $this->data[$this->alias]['enabled']
This code, however, seems to do the job just fine:
public function compareDates() {
if ($this->data[$this->alias]['enabled'] != 1) return true; // we don't want to check
return $this->data[$this->alias]['firstPageEnterDate'] < $this->data[$this->alias]['firstPageLeaveDate'];
}
What is, in your understanding, the meaning of "we don't want to check"?
Why: if ($this->data[$this->alias]['enabled'] == 1) is not enough?
Can anyone care to explain?
Update:
If I do:
public function compareDates()
{
if ($this->data[$this->alias]['enabled'] === "1") {
return $this->data[$this->alias]['firstPageEnterDate'] < $this->data[$this->alias]['firstPageLeaveDate'];
} else {
return true;
}
}
It works as well. My question is:
Why do I need to explicitly declare the return true?;
You're doing a simple comparison (==) so PHP is looking for "truthy" statements. So ANY value that is not "falsey" will evaluate your statement (i.e. 0, false, empty strings, NULL). You can find a complete list here.
The best way around this is to use equivalency to ensure it's the exact value you want
if ($this->data[$this->alias]['enabled'] === 1)
That will force PHP to look for an integer of 1. Be aware, though, that your value MUST be the same. In other words
if('1' === 1)
Is always false because string 1 is not the same as integer 1

PHP if status and !isset or !isset

I'm trying to match a condition where if the user status is 10 and ANY POST variables are not set it triggers an error:
if ($_SESSION['status']=='10' && !isset($_POST['a']) || !isset($_POST['B'])) {}
I can not use && conditions for any !isset as one variable may be set though another might not. I only want the condition to match if one or more variables are not set AND the status==10.
When testing if a $_POST variable !isset, I remove an input element from the page via a browser web tool (e.g. Firebug). When the form is submitted with the variable missing it's still passing validation incorrectly.
I am also seeking a PHP if grouping condition.
If you are looking for absolutely any PHP variables, I'd recommend this:
if (($_SESSION['status'] == 10) && (count($_POST) > 0)) {
You can then get the list of _POST var keys using array_keys($_POST).
If you are looking for a specific:
if (($_SESSION['status'] == 10) && (isset($_POST['A']) || isset($_POST['b']))) {
The order of the brackets is important. You can separate groups of logical statements with brackets.
Is that was what you were looking for?
$status = $_SESSION['status'];
if($status == '10'){
if(!isset($_POST['a']) or !isset($_POST['B'])){
//Triggers error.
}else{
//Another
}
}
Try making it a function:
function checkAllVars($dataVars, $requestVars) {
foreach($dataVars as $varname) {
if(!isset($requestVars[$varname])) {
return false;
}
}
return true;
}
$dataVars = array (
"varName1",
"varName2",
"varName3",
"varName4",
);
$allVarsSet = checkAllVars($dataVars, $_REQUEST);
you might be looking for
if($_SESSION['status']=='10' && (!isset($_POST['a']) || !isset($_POST['B']))){}
^ ^
which means if status = 10 and (if not set 'a' or not set 'B' or they can be both not set) do something
or you might be looking for
if(($_SESSION['status']=='10' && !isset($_POST['a'])) || ($_SESSION['status']=='10' && !isset($_POST['B']))){}

PHP operators if statement 'and' and 'or'

I have an if statement that I want to control with having one field needing input and they have to pick one of the other 2 choices.
if(test1 && test || test3){
//Something here
}
Should I do it like this:
if(test1 && (test2 || test3)){
//do stuff
}
How would I go about doing this. I can't wrap my head around the logic...
if ($requiredField && ($optional1 || $optional2)) {
/* Do something */
}
For the /* Do something */ bit of code to be executed, the if statement has to evaluate to TRUE.
This means, that $requiredField must be TRUE, and so must be ($optional1 || $optional2).
For $requiredField to be TRUE, it just needs to be filled in - and for the second part: ($optional1 || $optional2) either optional1 or optional2 would do it.
Edit:
After rereading the question, it seems that I might have misunderstood you. If the user must enter one specific piece of information, and must choose only one (not both) out of two options - then the following should be used.
if ($requiredField && ($optional1 ^ $optional2)) {
/* Do something */
}
This means that $optional1 or $optional2 must be filled out - but not both of them.
From the sound of it, you want the latter:
if ($test1 && ($test2 || $test3)){
//do stuff
}
Think of it as two conditions needing to be met. This gives you those two conditions. The second condition just happens to be another condition. The first option you posted, however, is quite the opposite as it can allow execution if just $test3 is true
test1 && (test2 || test3) is very easy to understand from the first place - Choose test1 && (test2 || test3) means one the last two. Very clear.
test1 && test || test3 - doesn't seem to be correct:
test1 = false
test2 = false
test3 = true
false && false || true = true
doesn't actually fit your criteria.
... they have to pick one of the other 2 choices
I'm just throwing a guess out here. If you really want to ensure that one, but only one of the two other options are selected, then you need xor:
if ($required AND ($and_either XOR $or_other)) {
You can have 'nested' if statements withing a single if statement, with additional parenthesis.
if(test1 && (test2 || test3)){
//do stuff
}
Your logic is right but your sintax isnt, you should compare the values of the variables as show, or simply ignore them as saying you are trying to compare them as they are TRUE.
$test1=true;
$test2=true;
$test3=false;
if($test1==true && ($test2==true || $test3==true){ echo "YES";}
This will output YES.

Categories