Two if statements using ternary condition - php

The title seems confusing but this is my first time using ternary conditions. I've read that ternary is meant to be used to make an inline if/else statement. Using no else is not possible. Is it true?
I want to change this with ternary condition for practice
if (isset($_SESSION['group']
{
if ($_SESSION['item'] == 'A')
{
echo "Right!";
}
}
It has two if statements only. The second if is nested with the other. I've also read that to make a no else possible for ternary, it just have to be set to null or empty string.

It's a bad example because you can use an AND-operator on the nested if:
$result = isset($_SESSION['group'] && $_SESSION['item'] == 'A' ? true : false;
Of course you can nest ternary operator, too:
$result = isset($_SESSION['group'] ? ( $_SESSION['item'] == 'A' ? true : false ) : false;
with echo
echo isset($_SESSION['group'] ? ( $_SESSION['item'] == 'A' ? "Right!" : "false" ) : "false";

echo (isset($_SESSION['group']) && $_SESSION['item'] == 'A') ? "Right" : ""
Better still (readable, maintainable), use:
if (isset($_SESSION['group']) && $_SESSION['item'] == 'A')
{
echo "Right!";
}

isset($_SESSION['group'] ? (if ($_SESSION['item'] == 'A') ? echo "Right" : null) : null
Try this, I think it might work =].
For further reading on ternary conditions in Java/ whatever you're using look at http://www.devdaily.com/java/edu/pj/pj010018

You can nest two ternary statements as this example:
echo (isset($_SESSION['group']))?($_SESSION['item']== 'A')?'Right!':null:null;

Did you know you can do this as well? (isset($_SESSION['group']) && ($_SESSION['item']=='A')) &&($result$c= 1); or echo (isset($_SESSION['group']) && ($_SESSION['item']=='A')) ? 'Hello!':'World!';

Related

how to check if variable is empty in php [duplicate]

if ($user_id == NULL || $user_name == NULL || $user_logged == NULL) {
$user_id = '-1';
$user_name = NULL;
$user_logged = NULL;
}
if ($user_admin == NULL) {
$user_admin = NULL;
}
Is there any shortest way to do it ?
And if i right, it should be tested with is_null?
It's possible $user_id, $user_name and $user_logged write in one line (maybe array?) without repeating NULL ?
If you want to test whether a variable is really NULL, use the identity operator:
$user_id === NULL // FALSE == NULL is true, FALSE === NULL is false
is_null($user_id)
If you want to check whether a variable is not set:
!isset($user_id)
Or if the variable is not empty, an empty string, zero, ..:
empty($user_id)
If you want to test whether a variable is not an empty string, ! will also be sufficient:
!$user_id
You can check if it's not set (or empty) in a number of ways.
if (!$var){ }
Or:
if ($var === null){ } // This checks if the variable, by type, IS null.
Or:
if (empty($var)){ }
You can check if it's declared with:
if (!isset($var)){ }
Take note that PHP interprets 0 (integer) and "" (empty string) and false as "empty" - and dispite being different types, these specific values are by PHP considered the same. It doesn't matter if $var is never set/declared or if it's declared as $var = 0 or $var = "". So often you compare by using the === operator which compares with respect to data type. If $var is 0 (integer), $var == "" or $var == false will validate, but $var === "" or $var === false will not.
here i have explained how the empty function and isset works please use the one that is appropriate also you can use is_null function also
<?php
$val = 0;
//evaluates to true because $var is empty
if (empty($val)) {
echo '$val is either 0, empty, or not set at all';
}
//evaluates to true because $VAR IS SET
if (isset($val)) {
echo '$val is set even though it is empty';
}
?>
empty() is a little shorter, as an alternative to checking !$user_id as suggested elsewhere:
if (empty($user_id) || empty($user_name) || empty($user_logged)) {
}
To check for null values you can use is_null() as is demonstrated below.
if (is_null($value)) {
$value = "MY TEXT"; //define to suit
}
Please define what you mean by "empty".
The test I normally use is isset().
you can use isset() routine .
also additionaly you can refer an range of is_type () functions like
is_string(), is_float(),is_int() etc to further specificaly test
1.
if(!($user_id || $user_name || $user_logged)){
//do your stuff
}
2 . No. I actually did not understand why you write such a construct.
3 . Put all values into array, for example $ar["user_id"], etc.
<?php
$nothing = NULL;
$something = '';
$array = array(1,2,3);
// Create a function that checks if a variable is set or empty, and display "$variable_name is SET|EMPTY"
function check($var) {
if (isset($var)) {
echo 'Variable is SET'. PHP_EOL;
} elseif (empty($var)) {
echo 'Variable is empty' . PHP_EOL;
}
}
check($nothing);
check($something);
check($array);
Its worth noting - and I only found this out after nearly 9 years of PHP coding that the best way of checking any variable exists is using the empty() function. This is because it doesn't generate errors and even though you turn them off - PHP still generates them! empty() however won't return errors if the variable doesn't exist. So I believe the correct answer is not to check if its null but to do the following
if (!empty($var) && is_null($var))
Note the PHP manual
variable is considered empty if it does not exist or if its value equals FALSE
As opposed to being null which is handy here!
Felt compelled to answer this because of the other responses. Use empty() if you can because it covers more bases. Future you will thank me.
For example you will have to do things like isset() && strlen() where instead you could use empty(). Think of it like this empty is like !isset($var) || $var==false
The best and easiest way to check if a variable is empty in PHP is just to use the empty() function.
if empty($variable)
then
....

PHP Short If Statment with OR

I have the following PHP script
<?php
echo (($statusSet) == 'all') ? "class='selected'": "";
?>
What I would like to do is include an OR into this to say where $statusSet is equal to all OR NULL
Im competely lost with hwo to write this as I tried adding the normal type of OR statement which didnt work
<?php
echo ((($statusSet) == 'all')||(($statusSet) == 'all'))) ? "class='selected'": "";
?>
All you're doing is adding another expression to be evaluated in the overall if statement.
<?php echo (($statusSet == 'all' || $statusSet === null) ? "class='selected'": ""); ?>
Someone below posted a nearly-identical snippet to mine, but used is_null() instead. Note that using is_null() or === null is fine, but using == null isn't best practices - it won't ensure type equality so if $statusSet was set to (int)0, doing $statusSet == null would return true when it's actually not a null value.
So like this?
echo $statusSet == 'all' || $statusSet === NULL ? "class='selected'": "";?>
I'm not sure that you copied the correct line into the question, but the reason that yours isn't working is because the two conditions are exactly the same, hence if one is true then then so is the other.
<?php echo (($statusSet == 'all') || (is_null($statusSet)) ) ? "class='selected'": "";?>

how to nest if and else statement using ternary operator in PHP?

am confused with using this ternary operator, i can easily get 1 level if and else
e.g
($blah == $blah) ? blahblah : blahblahblah;
but what if the condition is like this?
if($blah == blah1)
{
echo $blah1;
}
else if($blah == blah2)
{
echo $blah2;
}
else
{
echo $blah;
}
how to convert this using ternary operator ?
<?php echo $blah == 'blah1' ? $blah1 : ($blah == 'blah2' ? $blah2 : $blah); ?>
Notice how the else is wrapped in parenthesis. This can be done again and again, although it becomes confusing to read.
Nested ternaries are a bad idea. They're provided for brevity. If you have nested conditions, you by definition do not have brevity.
Some folk don't even like their use when you have a concise statement. Personally I find the following more clear and readable than the if-based alternative.
echo $success ? 'Success' : 'Failure';
But I would hesitate to do anything more complex than that.
($blah == $blah1) ? $blah1 : (($blah == $blah2) ? $blah2 : $blah);
It would become:
echo (($blah == $blah1) ? $blah1 : (($blah == blah2) ? $blah2 : $blah);

The use of "?" and ":"

I've read through a lot of code where they have if statements, i've noticed other languages use this to. Asp being one.
Tried googling but couldn't find a answer for it.
What exactly does ?: stand for and when to use it.
As far as I'm aware ? is equal to if() and : being equal to }else{.
It is the ternary operator (although in most languages it is better-named as the "conditional operator").
People will often erroneously refer to it as "shorthand if/else". But this is a misnomer; if/else is a statement, ?: is an expression. In most languages, these are distinct concepts, with different semantics.
This is called ternary operator.
It is meant to simplify code in some cases. Consider this:
var str;
if(some_condition)
str = 'yes';
else
str = 'no';
This can be easily rewritten as
var str = some_condition ? 'yes' : 'no';
Your assumption is right.
It is a Ternary operation (Wikipedia)
Essentially, the syntax is condition ? then-expession : else-expression. Typically it is used in assigning variables:
varname = something == 123 ? "yes" : "no";
But it can be used pretty much anywhere in place of a value. It's mostly useful for avoiding repetitive code:
if( something == 123) {
varname = "yes";
}
else {
varname = "no";
}
You could read the documentation. The section you're looking for is titled "Ternary Operator".
You can express calculations that might otherwise require an if-else construction more concisely by using the conditional operator. For example, the following code uses first an if statement and then a conditional operator to check for a possible division-by-zero error before calculating the sin function.
if(x != 0.0) s = Math.Sin(x)/x; else s = 1.0;
s = x != 0.0 ? Math.Sin(x)/x : 1.0;
from http://msdn.microsoft.com/en-us/library/ty67wk28(v=vs.90).aspx
In Java, it's an if/else relationship.
An example of a ternary operation:
boolean bool = (x==1) ? true : false;
http://en.wikipedia.org/wiki/Ternary_operation

Multiple conditions in the ternary operator safe?

I have seen advice that says the ternary operator must not be nested.
I have tested the code below and it works okay. My question is, I haven't seen the ternary operator used like this before. So, is this as reliable as it were used in an if or could something like this come and bite me later(not in terms or readability, but by failing).
$rule1 = true;
$rule2 = false;
$rule3 = true;
$res = (($rule1 == true) && ($rule2 == false) && ($rule3 == true)) ? true : false;
if($res) {
echo "good";
} else {
echo "fail";
}
Thanks!
If the results you are returning from the ternary operator are only "true" and "false", then you don't even need the operator. You can just have:
$res = (($rule1 === true) && ($rule2 === false) && ($rule3 === true))
But, to answer your question, yes multiple conditions work perfectly well.
It's totally legal, it works and is "as reliable as if", but it looks ugly.
If you put each ternary statement inside parenthesis, nesting would be fine too:
$res = ( $rule1 ? true : ( $rule2 ? true : false ) )
The only thing that is advised against in the manual is nesting without parenthesis like this:
$res = ( $rule1 ? true : $rule2 ? true : false )
Is there a reason you want to have your conditions saved into a variable? this is the simplified version of above.
if($rule1 && !$rule2 && $rule3)
{
echo "good";
}
else
{
echo "bad";
}
You do not need the ternary if you are going to return true or false. Quoting the manual:
The expression (expr1) ? (expr2) : (expr3) evaluates to expr2 if expr1 evaluates to TRUE, and expr3 if expr1 evaluates to FALSE.
This means
$res = (($rule1 == true) && ($rule2 == false) && ($rule3 == true));
will assign true or false already. Also, if dont care about $rule being booleans, you dont need the comparison with ==. You also dont need the braces, e.g.
$res = $rule1 && !$rule2 && $rule3;
is the same as your initial ternary.
A good practise when you have multiple expressions like that is to hide the actual comparison behind a meaningful method or function name, e.g.
function conditionsMet($rule1, $rule2, $rule3) {
return $rule1 && !$rule2 && $rule3;
}
and then you can do
if (conditionsMet($rule1, $rule2, $rule3)) {
// do something
}
Of course, conditionsMet isnt that meaningful. A better example would be something like isSummerTime or isEligibleForDiscount and so on. Just express what the rules express in the method name.
You might also be interested in Simplifying Conditional Expressions from the book Refactoring - Improving the design of existing code.
You can also do
$res = ($rule1 && !$rule2 && $rule3);
It's legal and doesn't have to be "ugly". I use the "hook" operator often, in table form it's quite clean, e.g.:
bool haveANeed()
{
// Condition result
// ---------- ------
return needToEat() ? true
: needToSleep() ? true
: needToStudy() ? true
: needToShop() ? true
: needToThink() ? true
: false; // no needs!
}
This function would, IMHO, be less clear and certainly longer if written with if-else logic.

Categories