I want to evaluate a simple ternary operator inside of a string and can't seem to find the correct syntax.
My code looks like this:
foreach ($this->team_bumpbox as $index=>$member)
echo ".... class='{((1) ? abc : def)}'>....";
but I can't seem to get it to work properly. Any ideas on how to implement this?
You can't do it inside the string, per se. You need to dot-concatenate. Something like this:
echo ".... class='" . (1 ? "abc" : "def") . "'>....";
Well, you can do it actually:
$if = function($test, $true, $false)
{
return $test ? $true : $false;
};
echo "class='{$if(true, 'abc', 'def')}'";
I'll let you decide whether it is pure elegance or pure madness. However note that unlike the real conditional operator, both arguments to the function are always evaluated.
Related
I want to check if the usr_name of user is empty, then get his email and adjust a new variable to it.
So here is the traditional way:
if(auth()->user()->usr_name != null){
$user_input = auth()->user()->usr_name;
}else{
$user_input = auth()->user()->usr_email;
}
Now I want to write this with ternary condition operators, so I tried this:
$user_input = empty(auth()->user()->usr_name) ? auth()->user()->usr_name : auth()->user()->usr_email;
But this is wrong, since it returns null for $user_input.
So what is the correct way of writing this with ternary operators?
$user_input = auth()->user()->usr_name ?: auth()->user()->usr_email;
Ternary operator has a short syntax in PHP. The above code is the same as
if (auth()->user()->usr_name) {
$user_input = auth()->user()->usr_name;
} else {
$user_input = auth()->user()->usr_email;
}
Which is most likely equivalent to your code, considering the non strict != null check.
Tenary operator check the result before "?" and if true returns first pair distinguished with ":" if not return second pair.
Let say A = true
C = A ? 1: 2 ;
here C equals to 1
In your example you must changed order of tenary result values
$user_input = empty(auth()->user()->usr_name) ?auth()->user()->usr_email : auth()->user()->usr_name
You just have your logic back to front
$user_input = empty(auth()->user()->usr_name) ? auth()->user()->usr_email : auth()->user()->usr_name;
So to be clear, you are giving priority to usr_name if it is set, otherwise use the usr_email
Note that you could put this in an accessor and then call something like auth()->user()->identifier anywhere in your project
If you use PHP >= 7.0 you could use the null-coalescing operator to write a really beautiful statement instead.
It would look something like:
$user_input = auth()->user()->usr_name ?? auth()->user()->usr_email;
I have this code
$myvar = is_object($somevar) ? $somevar->value : is_array($somevar) ? $somevar['value'] : '';
issue is that sometime I am getting this error
PHP Error: Cannot use object of type \mypath\method as array in /var/www/htdocs/website/app/resources/tmp/cache/templates/template_view.html.php on line 988
line 988 is the above line I included. I am already checking if its object or array, so why this error then?
It has something to do with priority, or the way PHP is evaluating your expression. Grouping with parentheses solves the problem:
$myvar = is_object($somevar) ? $somevar->value : (is_array($somevar) ? $somevar['value'] : '');
See the notes here: http://www.php.net/manual/en/language.operators.comparison.php#language.operators.comparison.ternary
Note:
It is recommended that you avoid "stacking" ternary expressions. PHP's
behaviour when using more than one ternary operator within a single
statement is non-obvious:
Example #3 Non-obvious Ternary Behaviour
<?php
// on first glance, the following appears to output 'true'
echo (true?'true':false?'t':'f');
// however, the actual output of the above is 't'
// this is because ternary expressions are evaluated from left to right
// the following is a more obvious version of the same code as above
echo ((true ? 'true' : false) ? 't' : 'f');
// here, you can see that the first expression is evaluated to 'true', which
// in turn evaluates to (bool)true, thus returning the true branch of the
// second ternary expression.
?>
You need to place parenthesis around the second ternary:
$myvar = is_object($somevar) ? $somevar->value : (is_array($somevar) ? $somevar['value'] : '');
This must have something to do with operator precedence, though I'm not sure why yet.
Opinion: The ternary with or without parenthesis is difficult to read IMHO. I'd stick with the expanded form:
$myvar = '';
if(is_object($somevar)) {
$myvar = $somevar->value;
} elseif(is_array($somevar)) {
$myvar = $somevar['value'];
}
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
I am trying to print out yes if a boolean table field from a database query is true, and no if it is false.
I am doing this:
echo "<td>"{$row['paid'] ? 'Yes' : 'No'";}</td>";
Why is this incorrect?
echo "<td>".(($row['paid']) ? 'Yes' : 'No')."</td>";
Personally, i never echo HTML so i would do this:
<td><?=(($row['paid']) ? 'Yes' : 'No')?></td>
Just a preference thing though..
echo "<td>".(($row['paid']) ? 'Yes' : 'No')."</td>";
Other guys have corrected your mistake, but I thought you might like to know why.
Your use of a ternary isn't actually the problem, it's the way you join it to the other stuff.
Echo is a function that takes one variable; a string. It's actually this (although people tend to leave the brackets off):
echo(SomeString);
In your case, SomeString needs to be "" followed by the outcome of your ternary, followed by "". That's three strings, which need to be glued together into one string so that you can "echo()" them.
This is called concatenation. In PHP, this is done using a dot:
"<td>" . (($row['paid']) ? 'Yes' : 'No') . "</td>"
Which can be placed inside an echo() like this:
echo("<td>" . (($row['paid']) ? 'Yes' : 'No') . "</td>");
Alternatively, you can skip concatenation by using a function that takes more than one string as a parameter. Sprintf() can do this for you. It takes a "format" string (which is basically a template) and as many variable strings (or numbers, whatever) as you like. Use the %s symbol to specify where it needs to insert your string.
sprintf("<td>%s</td>",(($row['paid']) ? 'Yes' : 'No'));
The world is now your oyster.
Ref this
echo "<td>".(($row['paid']) ? 'Yes' : 'No')."</td>";
Since echo takes many arguments, should use comma instead of string concatenation which takes more processing and memory:
echo "<td>", (($row['paid']) ? 'Yes' : 'No'), "</td>";
Does anybody know if there is a shortcut for the following statement in PHP?
$output = isset($some_value) ? $some_value : "Some Value Not Set";
echo $output;
This something that I often run into, where $some_value is actually very long and possibly involves a function, such as:
$output = $this->db->get_where('my_db',array('id'=>$id))->row()->some_value) ? $this->db->get_where('my_db',array('id'=>$id))->row()->some_value) : "Some Value Not Set";
echo $output;
It seems that there should be an operator or function that does this. I could easily write one, and I am not looking for that answer, but rather if anybody knows of a built-in shortcut.
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression expr1 ?: expr3 returns expr1 if expr1 evaluates to TRUE, and expr3 otherwise.
http://php.net/manual/en/language.operators.comparison.php
if you need to reuse the long expression from the test after the ?, you can assign it to a variable inside the test (because assignments are expressions returning the assigned value) and use this variable after the ?:
$output = ($some_value = $this->db->get_where('my_db', array('id' => $id))->row()->some_value))
? $some_value
: "Some Value Not Set";
echo $output;
You should be setting a variable with the results of your database call before using the conditional operator for this purpose. Your example makes the database call twice.
For example:
$output = $this->db->get_where('my_db',array('id'=>$id))->row()->some_value);
$output = $output ? $output : "Some Value Not Set";
echo $output;
And with that established, this is a good case where it's really wiser to not use the conditional operator, which really isn't meant to be used as a general purpose if-then shortcut.
You seem to be afraid of whitespace. Use it! Liberally! Your code is much eaiser to read if you add a space before and after the question mark and the colon, respectively. If your statements get too long, add a newline. Try it, it won't hurt you.
I do believe that the conditional operator is the shortcut :) For the sake of saving function calls and readability, I suggest saving the value to a variable first.
$some_value = $this->db->get_where('my_db',array('id'=>$id))->row()->some_value);
$output = $some_value ? $some_value : "Some Value Not Set";
echo $output;
Best way is to:
$output = $this->db->get_where('my_db',array('id'=>$id))->row()->some_value)
echo $output =($output)?$output:"Some Value Not Set";
Only executes once then!