I want to check the GET variables are not empty, I tried ways but they didn't work.
So I had the code like this:
$u = isset($_GET["u"]);
$p = isset($_GET["p"]);
if ($u !== "" && $p !== "") {
//something
} else {
//do something
}
The I checked the code by sending create.php?u=&p=, but the code didn't work. It kept running the //do something part. The I tried:
echo $u;
echo $p;
It returned 1 and 1. Then I changed it to:
if ($u !== 1 && $p !== 1 && $u !== "" && $p !== "") {
//something
} else {
//do something
}
But it continued to run //do something.
Please help.
You can just use empty which is a PHP function. It will automatically check if it exists and whether there is any data in it:
if(empty($var))
{
// This variable is either not set or has nothing in it.
}
In your case, as you want to check AGAINST it being empty you can use:
if (!empty($u) && !empty($p))
{
// You can continue...
}
Edit: Additionally the comparison !== will check for not equal to AND of the same type. While in this case GET/POST data are strings, so the use is correct (comparing to an empty string), be careful when using this. The normal PHP comparison for not equal to is !=.
Additional Edit: Actually, (amusingly) it is. Had you used a != to do the comparison, it would have worked. As the == and != operators perform a loose comparison, false == "" returns true - hence your if statement code of ($u != "" && $p != "") would have worked the way you expected.
<?php
$var1=false;
$var2="";
$var3=0;
echo ($var1!=$var2)? "Not Equal" : "Equal";
echo ($var1!==$var2)? "Not Equal" : "Equal";
echo ($var1!=$var3)? "Not Equal" : "Equal";
echo ($var1!==$var3)? "Not Equal" : "Equal";
print_r($var1);
print_r($var2);
?>
// Output: Equal
// Output: Not Equal
// Output: Equal
// Output: Not Equal
Final edit: Change your condition in your if statement to:
if ($u != "" && $p != "")
It will work as you expected, it won't be the best way of doing it (nor the shortest) but it will work the way you intended.
Really the Final Edit:
Consider the following:
$u = isset($_GET["u"]); // Assuming GET is set, $u == TRUE
$p = isset($_GET["p"]); // Assuming GET is not set, $p == FALSE
Strict Comparisons:
if ($u !== "")
// (TRUE !== "" - is not met. Strict Comparison used - As expected)
if ($p !== "")
// (FALSE !== "" - is not met. Strict Comparison used - Not as expected)
While the Loose Comparisons:
if ($u != "")
// (TRUE != "" - is not met. Loose Comparison used - As expected)
if ($p != "")
// (FALSE != "" - is met. Loose Comparison used)
You need !empty()
if (!empty($_GET["p"]) && !empty($_GET["u"])) {
//something
} else {
//do something
}
Helpful Link
if ($u !== 1 && $p !== 1 && $u !== "" && $p !== "")
why are you using "!==" and not "!=".
to always simplify your problem solve the logic on paper once using the runtime $u and $p value.
To check if $_GET value is blank or not you can use 2 methods.
since $_GET is an array you can use if(count($_GET)) if you have only u and p to check or check all incoming $_GET parameters.
empty function #Fluffeh referred to.
if($_GET['u']!=""&&$_GET['p']!="")
Hope it helps thx
In you code you should correctly check the variable existence like
if ($u != NULL && $p != NULL && $u != 0 && $p != 0) {
//something
} else {
//do something
}
Wow! I was so dumb... isset returns a boolean. I fixed my problem now. Thank you for answering anyway :)
This fixes:
$u = $_GET["u"];
$p = $_GET["p"];
Related
I'm using this in my code but I think it can be improved and can be done a simpler way?
if($phaseOne == true && $phaseTwo == true && $phaseThree == true) {
}
You can do it like this:
if($phaseOne && $phaseTwo && $phaseThree) { ... }
Or use ternary operator, if you're trying to define a variable on the basis of these conditions like this:
$var = ($phaseOne && $phaseTwo && $phaseThree) ? true : false;
Hope this helps!
Assuming you have an array with an arbitrary number of logical variables:
$logical = array($phraseOne,$phraseTwo,....);
$allTrue = array_reduce($logical, function ($x,$y) {return $x && $y;},true);
if($allTrue) {
}
Do just:
if($phaseOne && $phaseTwo && $phaseThree)
You don't need to compare it against true.
if ($phaseOne && $phaseTwo && $phaseThree) {
}
This occurs because the result of any comparison is a boolean:
var_dump(1 == 1); // bool(true)
var_dump(1 == 2); // bool(false)
Also if you variable contains a number, it can be used directly:
if (1) {
// This will be executed
}
if (0) {
// This will not be executed
}
Zero will be always be treated as false, any other number (positive or negative) will be true.
Unless you need to check each variable as explicitly identical to a boolean or variable, (see this stack overflow thread)
I'd do it this way
if ($phaseOne && $phaseTwo && $phaseThree) {}
Otherwise, I'd do it this way
if ($phaseOne === true && $phaseTwo === true && $phaseThree === true) {}
Try with this:
($phaseOne && $phaseTwo && $phaseThree) ? {//do something} : '';
Although I think it is arbitrary, controlversial, trivial, and won't preach the use of this, just for fun and learning - here's some typical php variable type juggling that will work also and takes up the least space... efficient in terms of source code length.
if($phaseOne*$phaseTwo*$phaseThree) { ... }
This below is printing hello even though the statement is false
$Originating_country_region = $country_region[$i]['region']; // value of var is AM after assigning
$order_shipping_country_region = $country_region[$i]['region']; // value of var is EU after assigning
if(isset($Originating_country_region) == "EU" && isset($order_shipping_country_region) == "EU")
{
echo "Hello";
}
You're testing the return value of isset, and not the contents of the variables directly. Try:
if((isset($Originating_country_region) && $Originating_country_region) == "EU") && (isset($order_shipping_country_region) && $order_shipping_country_region == "EU"))
This checks that the codes are first of all set, and then checks their values.
It's a useful trick to learn :-)
I have string $a,$b,$c
I know if all of them not null express in this way:
if($a!="" && $b!="" && $c!="")
But if either 2 of them not null then go into the true caluse
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(either 2 are not null){
**do another things here**
}
How to express it?
I would write a simple function like this to check:
function checkInput($var)
{
$nulls=0;
foreach($var as $val)
{
if(empty($val))
{
$nulls++;
}
}
return $nulls;
}
Then access it like this:
$inputs=array($a, $b, $c.... $z);
$nullCount=checkInput($inputs);
if($nullCount==0)
{
// All nulls
}
if($nullCount>2)
{
// More than 2 nulls
}
or for an one-off test, just pop the function into the actual if statement like this:
if(checkInput($inputs)>2)
{
// More than 2 nulls...
}
etc etc. You can then use the one function to check for any number of nulls in any number of variables without doing much work - not to mention change it without having to rewrite a long if statement if you want to modify it.
Other answers are good, but you can expand this to easily handle more variables:
$variables = array($a, $b, $c, $d, ....);
$howManyNulls = 0;
foreach($variables as $v){
if($v == ''){
$howManyNulls++;
}
}
if($howManyNulls == count($variables) - 2){
// do stuff
}
you can try this
if($a!="" && $b!="" && $c!="")
{
** do the things here **
}
else if(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!=""))
{
**do another things here**
}
Try:
if($a!="" && $b!="" && $c!=""){
** do the things here **
}else if(($a!="" && $b!="") || ($a!="" && $c!="") || ($b!="" && $c!="")){
**do another things here**
}
$var[] = empty($a) ? 0:$a;
$var[] = empty($b) ? 0:$b;
$var[] = empty($c) ? 0:$c;
$varm = array_count_values($var);
if ($varm[0] === 0) {
//Code for when all aren't empty!
} elseif ($varm[0] === 1) {
//Code for when two aren't empty!
}
N.B; You may need to replace the 0 for a string/integer that will never crop up, if your variables are always strings or empty then 0 will do for this. The method for using bools within this would require more code.
$nullCount = 0
if($a!=""){ ++$nullCount; }
if($b!=""){ ++$nullCount; }
if($c!=""){ ++$nullCount; }
if($nullCount == 3){ // all are null
// do smth
}else if($nullCount == 2){ // only two are null
// do other
}
Just for fun, here's something potentially maintainable, should the list of arguments increase:
function countGoodValues(...$values) {
$count = 0;
foreach($values as $value) {
if($value != "") {
++$count;
}
}
return $count;
}
$goodValues = countGoodValues($a, $b, $c); // Or more... or less
if($goodValues == 3) {
// Do something here
}
else if($goodValues == 2) {
// And something else
}
Reference for the ... construct (examples #7 and #8 in particular) are available on php.net.
You can use double typecasting (to boolean, then to number) in conjunction with summing:
$count = (bool)$a + (bool)$b + (bool)$c;
if ($count == 3)
// ** do the things here **
else if ($count == 2)
//**do another things here**
There is also possible such solution:
<?php
$a= 'd';
$b = 'a';
$c = '';
$arr = array( (int) ($a!=""), (int) ($b!=""), (int) ($c!=""));
$occ = array_count_values($arr);
if ($occ[1] == 3) {
echo "first";
}
else if($occ[1] == 2) {
echo "second";
}
If you have 3 variables as in your example you can probably use simple comparisons, but if you have 4 or more variables you would get too big condition that couldn't be read.
if (($a!="") + ($b!="") + ($c!="") == 2) {
// two of the variables are not empty
}
The expression a!="" should return true (which is 1 as an integer) when the string is not empty. When you sum whether each of the strings meets this condition, you get the number of non-empty strings.
if (count(array_filter([$a, $b, $c])) >= 2) ...
This is true if at least two of the variables are truthy. That means $var == true is true, which may be slightly different than $var != "". If you require != "", write it as test:
if (count(array_filter([$a, $b, $c], function ($var) { return $var != ""; })) >= 2) ...
if($a!="" && $b!="" && $c!="") {
echo "All notnull";
} elseif(($a!="" && $b!="") || ($b!="" && $c!="") || ($a!="" && $c!="")) {
echo "Either 2 notnull";
}
I have simple code which is something like this:
$options = new Options();
$page = new Pages();
if($page->page_limit() <= $options->pageno) {
$page->userid = $user_details->userid;
$page->date_of_pub = $_POST['date_of_pub'];
$resultss=$page->page_create();
}
else {
$resultss=false;
}
Then at bottom I am putting a condition
if(isset($resultss) && isset($resultss) == true) {
echo $alert->SuccessMsg("Page created successfully!");
}
if(isset($resultss) && isset($resultss) == false) {
echo $alert->ErrorMsg("You Have Been Reached to your maximum page limit");
}
Instead of printing error value even I have set the value of $result = false is shows success message, means its showing $resultss = true statement.
Suggest something. This is so strange. I got the answer thank you so much :)
One more thing.
can you please tell me how can I get rid of this " echo $alert->ErrorMsg" this is so annoying for all the class and functions. I want to make it a single word.
You check the same twice:
isset($resultss) && isset($resultss)==true
You should do:
isset($ressults) && $ressults == true
You have a problem in your logic with isset(). This:
if(isset($resultss) && isset($resultss)==true){echo $alert->SuccessMsg("Page created successfully!");}
if(isset($resultss) && isset($resultss)==false){echo $alert->ErrorMsg("You Have Been Reached to your maximum page limit");}
Should be
if(isset($resultss) && $resultss == true){echo $alert->SuccessMsg("Page created successfully!");}
if(isset($resultss) && $resultss ===false){echo $alert->ErrorMsg("You Have Been Reached to your maximum page limit");}
In your existing code, the second isset() in each statement is incorrect. In the first one, it is redundant, and you are asking the same thing as if(isset($resultss) && isset($resultss)), which is always true. In the second one, isset($resultss) && isset($resultss)==false could never be true. It's like true && false.
You really don't need to check if the variables are set, since you are setting it in both branches of the if/else. Just do:
if ($resultss) {
echo $alert->SuccessMsg("Page created successfully!");
} else {
echo $alert->ErrorMsg("You Have Been Reached to your maximum page limit");
}
Change your IF conditions to:
if(isset($resultss) && $resultss == true)
isset(x) and isset(x) == true bacially mean the same. What you want is to match two conditions:
the variable IS SET and IT IS EQUAL TO TRUE.
Since I'm not sure what the value might be I'd suggest using these confitions:
if(isset($resultss) && $resultss !== false) //the value is set and it is NOT set to false
AND
if(isset($resultss) && $resultss === false) //the value is set to false
Have you tried setting it to false as default?
$options = new Options();
$page = new Pages();
$resultss = false;
if($page->page_limit() <= $options->pageno){
$page->userid = $user_details->userid;
$page->date_of_pub = $_POST['date_of_pub'];
$resultss = $page->page_create();
}
I'm wondering if there is any way to make this code shorter. I'm using 2 if statements and I'm looking to only use one. The things is $user is the session and if you check if $user->userId exists on the same line, the code will error when no session exists. Caused by requesting the userId from an object that does not exist. That's pretty logical but now is there any solution?
if ($user != null) {
if ($user->userId == 1) {
..
}
}
How about using the && operator:
if ($user && $user->userId == 1) {
//...
}
You can add as many sentences as you want, as long as they are properly built, in this case:
if (($user != null) && ($user->userId == 1)) {
or you could simply:
if ($user && ($user->userId == 1)) {
if ($user) just checks if the variable is set, or if it is not null.
You want to use the && operator. It means and
if ($user && $user->userId == 1) {
// do some things
}
You may also want to look into the || operator, it means or.
The && operator will return true ONLY if the two predicates return true.
The || operator will return true as long as one of the predicates return true.