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) { ... }
Related
I have to evaluate a very long condition in PHP, so, to avoid errors and trying to write more readable code, I did the following:
//this returns 1 when true, and nothing when false, although expected TRUE or FALSE
$isNameValid=strlen($dataDecoded['nombre'])>=3;
$isDescriptionValid=(strlen($dataDecoded['descripcion'])>=10) && strlen($dataDecoded['descripcion'])<=300;
$isPriceValid=$dataDecoded['precio'] >0;
$isImageValid=(($dataDecoded['imagen'] != "") && ($dataDecoded['imagen'] != NULL) );
And now, I can make the following:
if($isNameValid==1 && $isDescriptionValid==1 && $isPriceValid==1 && $isImageValid==1)
{
echo "ok";
}
else{
echo "no";
}
It seems to work fine, but maybe is a weird way of doing things. I wanted to avoid the following, which I find more confusing and easy to make a mistake
if(strlen($dataDecoded['nombre'])>=3 && ... && ...)
Is there a better way to do that? Is wrong what I did? Thanks
I don't care for creating extra variables here; this makes code difficult to maintain and unreusable. I'd recommend breaking your validation logic into easy-to-read, maintainable, reusable functions:
function valid($data) {
return validName($data['nombre']) &&
validDescription($data['descripcion']) &&
validPrice($data['precio']) &&
validImage($data['imagen']);
}
function validName($name) {
return strlen($name) >= 3;
}
function validDescription($desc) {
return strlen($desc) >= 10 && strlen($desc) <= 300;
}
function validPrice($price) {
return $price > 0;
}
function validImage($image) {
return $image !== "" && $image != NULL;
}
$dataDecoded = [
"nombre" => "foo",
"descripcion" => "foo bar foo bar",
"precio" => 15,
"imagen" => "foo.png"
];
// now your main code is beautiful:
echo (valid($dataDecoded) ? "ok" : "no") . "\n";
Yes, that is acceptable. However, your variables there are all boolean, so you don't even need the ==1.
if($isNameValid && $isDescriptionValid && $isPriceValid && $isImageValid)
It really depends on how you want to handle it.
Is switch an option or a viable one?
Is ternary if prettier or handy?
From what I see, I'm guessing you have a validation purpose and a operating incoming depending on the validation. Why not create a function or a class that handles your input and validates? And in there, you can have all the dirty code you'd want. On your logical code, you'd just have to do (e.g of a class)
$someClass = new SomeClass();
$someClass->validate($fields);
if ($someClass->isValidated()) ...
This way, you'd actually follow some standards whereas the purpose of it would be to work as a validator for (all of? depends on your needs) your data
E.g of ternary ifs
$isNameValid = count($dataDecoded['nombre'])>=3 ? true : false;
$isDescriptionValid = count($dataDecoded['descripcion']) >= 10 && count($dataDecoded['descripcion']) <= 300 ? true : false;
$isPriceValid = count($dataDecoded['precio']) > 0 ? true : false;
$isImageValid = empty($dataDecoded['imagen']) === false ? true : false;
if ($isNameValid && $isDescriptionValid && $isPriceValid && $isImageValid) ...
I am trying to find an answer for a pretty simple question.
Is it possible to ask 2 things in 1 if / else statement?
For example:
if($a>$b AND isset($c))
return TRUE;
I understand it is possible to write it like:
if ($a>$b)
{
if (isset($c))
return TRUE;
}
I am looking for something easier and less messy to code. I am up for any advises.
Thanks.
Yes we have an && operator for this:
if($a > $b && isset($c)){
return true;
}
Yes you can as
if($a>$b && isset($c)){
return TRUE;
}
or
if($a>$b AND isset($c)){
return TRUE;
}
They do the same thing, but && has higher precedence than AND.
http://php.net/manual/en/language.operators.precedence.php
Yes it is possible. You can use && operator which will require both the conditions to be true so no need of that nested if . Just do -
if($a>$b && isset($c))
return TRUE;
if($a>$b && isset($c)
return TRUE;
Tou can do even with AND / OR opperators. Like:
if($v == 'asd' AND $b = 'asdsd') echo "Yes";
With the help of && operator :
if($a > $b && isset($c)){
return true;
}
Note: It will check that both conditions are true, if yes then only if block works. If you want that anyone of them true will lead to if block execution then go for || operator.
I have 2 URLs say
http://localhost/xyz?language=en
http://localhost/xyz?language=es
for which I want to check if language parameter has something other than en/es, then it should redirect to some http://localhost/xyz/errorpage
For this I have below code:
if(isset($_GET['language'])){
if(($_GET['language'] !== "en") || ($_GET['language'] !== "es")){
header('Location: /xyz/errorpage');
}
}
But practically when I execute the any of the 2 URLs or putting value of language parameter to something different than en/es:
http://localhost/xyz?language=en
http://localhost/xyz?language=es
http://localhost/xyz?language=esdfsdf
I am redirected to errorpage
Cannot understand the issue with code.
Replace || by &&.
The reason :
You want to redirect only if this is not en AND not es.
change the if statment to && instead of || or your condition will be always false.
if(isset($_GET['language'])){
if($_GET['language'] !== "en" && $_GET['language'] !== "es"){
header('Location: /xyz/errorpage');
}
}
You have bad condition, or better, operator.
Use && instead of ||, or in_array().
if(($_GET['language'] !== "en") && ($_GET['language'] !== "es")) {
Using in_array() function:
if (!in_array($_GET['languge'], array('en', 'es'))) {
header ();
}
Condition if ($a != 'x' || $a != 'y') is always true, first or the second part of condition has be true. There are no other ways.
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"];
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.