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.
Related
The best way to check the conditions and what is difference between them?
This is my usual way:
if ($this->_is_valid_number() == TRUE) {
//do some thing...
}
I've seen some code written in this way(for example):
if (TRUE == $this->_is_valid_number()) {
//do some thing...
}
Are these different from each other? Which method is standard?
None of the above, really.
== true is redundant with if(condition) so it could just be written as if ($this->_is_valid_number()) which is pretty standard. If you want to check for false, you would do if (!$this->_is_valid_number()) and if you would check for any other condition, you usually write like you would speak:
If my number is not one -> if($number !== 1)
Notice: Also check this article for difference between == and === operators
The second method has a added benefit of failing if it's used incorrect.
The second one sets true to $number and creates no error, which is what the code should do but not what the coder is expecting.
Do it the other way around and it will fail
$number =5;
if($number == true) echo "true"; // true
if($number = true) echo "true"; //true
if(true == $number) echo "true"; // true
if(true = $number) echo "true"; // fails
https://3v4l.org/suF9s
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'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) { ... }
the current page is getting the variables item and code from query string,so according to my code it should go into any of the first three conditions... but its going into the last else conditon.. while echoing the values $a and $i, i am getting 2 and A-1-1 respectively.
$a=$_GET['code'];
$i=$_GET['item'];
if($a==1 && $i!='')
{
header("location:http//:www.abc.com");
}
else if($a==2 && $i!='')
{
header("location:http://www.xyz.com");
}
else if($a==3 && $i!='')
{
header("location:http://www.xpqr.com");
}
else if($a==1)
{
header("location: http://www.a1bc.com");
}
else if($a==2)
{
header("location:http://www.x1yz.com");
}
else if($a==3)
{
header("location:http://www.x1pqr.com");
}
else
{
echo "ERROR";
}
can someone help me find the issue why the if else not working in the expected manner.
In conditions you are writing
if($a=1 && $i!='') // "=" is assignment operator
it should bt
if($a==1 && $i!='')
you need to use the equality operator: == double equal
if($a==1 && $i!='')
single equal is the assignment operator.
You are using assignment operator instead of a conditional operator.
For the above code the value of a will always be 1 because of the following line of code :
if($a=1 && $i!='')
= is an assignment operator where as == is a conditional operator.
Use == in all your if condition.
Hope this will help.
Use == in all your if condition. And your header codes
header("location: http:www.abc.com");
Should be like this
header("location: http://www.abc.com"); // you are missing '//' in every header
$a=$_GET['code'];
$i=$_GET['item'];
if($a==1 && !$i)
{
header("location:http//:www.abc.com");
}
else if($a==2 && !$i)
{
header("location:http://www.xyz.com");
}
else if($a==3 && !$i)
{
header("location:http://www.xpqr.com");
}
else if($a==1)
{
header("location: http://www.a1bc.com");
}
else if($a==2)
{
header("location:http://www.x1yz.com");
}
else if($a==3)
{
header("location:http://www.x1pqr.com");
}
else
{
echo "ERROR";
}
use !$i it sets to false.
Is there a function to check both
if (isset($var) && $var) ?
The empty() function will do the job.
Use it with the not operator (!) to test "if not empty", i.e.
if(!empty($var)){
}
You may use the ?? operator as such:
if($var ?? false){
...
}
What this does is checks if $var is set and keep it's value. If not, the expression evaluates as the second parameter, in this case false but could be use in other ways like:
// $a is not set
$b = 16;
echo $a ?? 2; // outputs 2
echo $a ?? $b ?? 7; // outputs 16
More info here:
https://lornajane.net/posts/2015/new-in-php-7-null-coalesce-operator
there you go. that should do it.
if (isset($var) && $var)
if (! empty($var))
It seems as though #phihag and #steveo225 are correct.
Determine whether a variable is considered to be empty. A variable is
considered empty if it does not exist or if its value equals FALSE.
empty() does not generate a warning if the variable does not exist.
No warning is generated if the variable does not exist. That means
empty() is essentially the concise equivalent to !isset($var) || $var
== false.
So, it seems !empty($var) would be the equivalent to isset() && $var == true.
http://us2.php.net/empty
Try the empty function:
http://us2.php.net/empty
isset($a{0})
isset AND len is not 0 seems more reliable to me, if you run the following:
<?php
$a=$_REQUEST['a'];
if (isset($a{0})) { // Returns "It's 0!!" when test.php?a=0
//if (!empty($a)) { // Returns "It's empty!!" when test.php?a=0
echo 'It\'s '.$a;
} else { echo 'It\'s empty'; }
?>
$a = new stdClass;
$a->var_false = false;
$a->var_true = true;
if ($a->notSetVar ?? false) {
echo 'not_set';
}
if ($a->var_true ?? false) {
echo 'var_true';
}
if ($a->var_false ?? false) {
echo 'var_false';
}
This way:
if (($var ?? false) == true) {
}
I am amazed at all these answers. The correct answer is simply 'no, there is no single function for this'.
empty() tests for unset or false. So when you use !empty(), you test for NOT UNSET (set) and NOT FALSE. However, 'not false' is not the same as true. For example, the string 'carrots' is not false:
$var = 'carrots'; if (!empty($var)){print 1;} //prints 1
in fact your current solution also has this type problem
$var = 'carrots'; if (isset($var) && $var){print 1;} //prints 1
as does even this
$var = '1.03'; if (isset($var) && $var == true){print 1;} //prints 1
in fact... if you want to do as you described exactly, you need:
$var = 'carrots'; if (isset($var) && $var === true){print 1;} //Note the 3 Equals //doesn't print 1
I suppose the shortest valid way to test this case is :
if (#$var === true){ print 1;}
But suppressing errors for something like this is pretty awful practice.
Don't know if an exact one already exists, but you could easily write a custom function to handle this.
function isset_and_true($var) {
return (isset($var) && $var == true) ? true : false;
}
if (isset_and_true($a)) {
print "It's set!";
}
Check if the variable is set, and true. Ignore warning message
if(#!empty($foo))