This question already has answers here:
Stacking Multiple Ternary Operators in PHP
(11 answers)
Closed 2 years ago.
I have this piece of code that is unclear to me, specifically the complex use of the ternary
operators
if (!$byField && is_numeric($v)){ // by ID
$r=$fromRow?
$fromRow:
($v?
dbRow("select * from pages where id=$v limit 1"):
array()
);
}
if someone could explain how to evaluate the nested use of ternary operators
Using nested ternary operators in your code adds unnecessary complexity. For the same reason, it should not be used. Just use a normal if-else block instead. That's far more readable.
if (condition) {
# code...
}
else {
# code...
}
To answer your question:
$r = $fromRow ? $fromRow : ( $v ? dbRow("..."): array() );
The above statement can be rewrote as follows:
if (!$byField && is_numeric($v))
{
if ($fromRow)
{
$r = $fromRow;
}
elseif ($v)
{
$r = dbRow("select * from pages where id=$v limit 1"):
}
else
{
$r = array();
}
}
As you can see, it's more readable.
Consider the following code:
<?php
$a = true;
$b = false;
$c = true;
echo (
$a
? 'A is true'
: (
$b
? 'A is false, but B is true'
: (
$c
? 'A is false, B is false, but C is true'
: 'A, B and C are all false'
)
)
);
?>
Which could easily be rewritten as so:
<?php
if ($a) {
echo 'A is true';
} else {
if ($b) {
echo 'A is false, but B is true';
} else {
if ($c) {
echo 'A is false, B is false but C is true';
} else {
echo 'A, B and C are all false';
}
}
}
?>
if (!$byField && is_numeric($v)){ // by ID
if ($fromRow) {
$r = $fromRow;
else if ($v) {
$r = dbRow("select * from pages where id=$v limit 1"):
} else {
$r = array();
}
}
Related
This question already has answers here:
Stacking Multiple Ternary Operators in PHP
(11 answers)
Closed 2 years ago.
I'm wondering if I could use the ternary operator for something like this:
var string = "";
if (something) {
string = "foo"
} else if (somethingElse) {
string = "bar";
} else if (bla) {
string = "pool";
} else if (xxxxx) {
string = "coffee";
} else {
string = "";
}
As far as I remember, I can do this in Java language:
String string = something?"foo":somethingElse?"bar":bla?"pool":xxxxx?"coffee":"";
But I'm not sure about PHP, I'm not even sure if it's OK to use ternary operator in this case or not.
E.g
if (something) {
string = "foo"
} else if (somethingElse) {
string = "bar";
} else if (bla) {
string = "pool";
} else if (xxxxx) {
string = "coffee";
} else {
string = "";
}
is equivalent to in PHP
(something) ? 'foo' : ((somethingElse) ? 'bar' : ((bla) ? 'pool' : ((xxxxx) ? 'coffe' : '')));
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";
}
This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 9 years ago.
if ($form->isValid()) {
// ... perform some action, such as saving the task to the database
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'task_new'
: 'task_success';
return $this->redirect($this->generateUrl($nextAction));
}
Here is the link to the documentation
http://symfony.com/doc/current/book/forms.html
The class documentation says that it returns a bool.
What is the point of
? 'task_new'
: 'task_sucess';
That is called "ternary" and it's awesome:
This is assigning the value $nextAction based on a condition. The first part (after the =) is the condition, like an if statement, the second part (after the ?) is the value assigned if the condition is true, and the last part (after the :) is the value assigned if the condition is false.
//the condition
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'task_new' //true value
: 'task_success'; //false value
It is a shorter way of writing this:
if ($form->get('saveAndAdd')->isClicked()) {
$nextAction = 'task_new';
}
else {
$nextAction = 'task_success';
}
So, here's some easy examples:
$foo = (true) ? 'True value!' : 'False value!';
echo $foo; //'True value!' of course!
$foo = (false) ? 'True value!' : 'False value!';
echo $foo; //'False value!' of course!
It's the Ternary operator. The syntax is as follows:
value = (condition) ? run if true : run if false;
In this case, if $form->get('saveAndAdd')->isClicked() is true, then task_new. Else task_success.
If could be rewritten like so:
if($form->get('saveAndAdd')->isClicked()) {
$value = "task_new";
} else {
$value = "task_success";
}
The ternary operator is a shorter form for an if statement.
The : is the "else" part.
Example in Java:
boolean bool;
true ? bool = true : bool = false;
It's a senseless example, but shows the ternary operator very well.
if the condition, here true is "true", then fill into the variable bool true, else false.
alternative if-statement in Java to the code example above:
boolean bool;
if(true)
bool = true;
else
bool = false;
This is a Ternary Operator which is a short hand if else statement. This is equivalent to
if($form->get('saveAndAdd')->isClicked()){
$nextAction = 'task_new'
else{
$nextAction = 'tassk_success'
}
This is the ternary opeator, a short-hand expression that works the same as an if
$value = someFunc() ? "whatever" : "the other"
is equivalent to
if (someFunc()) {
$value = "whatever";
} else {
$value = "the other";
}
This is equivalent to "if" and "else" statements.
This code :
$nextAction = $form->get('saveAndAdd')->isClicked()
? 'task_new'
: 'task_success';
is equivalent to this code :
if ( $form->get('saveAndAdd')->isClicked() )
{
$nextAction = 'task_new';
}
else
{
$nextAction = 'task_success';
}
I am just wondering if there is better way to solve my situatuion:
I have 6 independent variables to check. But if any of conditions is true it shouldnt check other. Normally I would write:
if (cond1 ) {
statement
} else {
if ( cond2 ) {
statement
} else {
if (cond3) {
statement
} else {
...
}
}
}
Surely you would admit it doesnt look good or it is not easy to read although it works. Do you know any other ways to write such if statement maybe using other notation or functions (switch? while?)
Yes, you can do
if (cond1 ) {
statement
} elseif ( cond2 ) {
statement
} elseif ( cond3 ) {
statement
}
See documentation
A more stylish way:
if(cond1):
statement1
elseif(cond2):
statement2
elseif(cond3):
statement3
elseif(cond4):
statement4
elseif(cond5):
statement5
elseif(cond6):
statement6
endif;
This is how you do it with a switch():
$a = 10;
$b = 100;
switch(true){
case ($a > $b):
echo 'a is bigger than b';break;
case ($b > $a):
echo 'b is bigger than a';break;
}
if (cond1 ) {
statement
} else {
if ( cond2 ) {
statement
} else {
if (cond3) {
statement
} else {
...
}
}
}
Change to:
if (Cond1){
}elseif (cond2){
}elseif (cond3){
}
How does PHP read if statements?
I have the following if statements in this order
if ( $number_of_figures_in_email < 6) {
-- cut: gives false
}
if($number_of_emails > 0) {
-- cut: gives false
}
if ( $number_of_emails == 0) {
-- cut: gives true
}
The code behaves randomly. It sometimes goes to the third if clause and gives me a success, while sometimes to the one of the first two if clauses when the input variables are constant.
This suggests me that I cannot code only with if statements.
It doesn't "behave randomly", it does what you tell it to do:
if ($a) {
// do A
}
if ($b) {
// do B
}
if ($c) {
// do C
}
All three ifs are independent of each other. If $a, $b and $c are all true, it'll do A, B and C. If only $a and $c are true, it'll do A and C, and so on.
If you're looking for more "interdependent" conditions, use if..else or nested ifs:
if ($a) {
// do A and nothing else
} else if ($b) {
// do B and nothing else (if $a was false)
} else if ($c) {
// do C and nothing else (if $a and $b were false)
} else {
// do D and nothing else (if $a, $b and $c were false)
}
In the above only one action will get executed.
if ($a) {
// do A and stop
} else {
// $a was false
if ($b) {
// do B
}
if ($c) {
// do C
}
}
In the above both B and C might get done, but only if $a is false.
This, BTW, is pretty universal and not at all PHP specific.
If you want to return only one of the results from many different if statements, use elseif, like this:
if ( $number_of_figures_in_email < 6) {
-- cut: gives false
}
elseif($number_of_emails > 0) {
-- cut: gives false
}
elseif ( $number_of_emails == 0) {
-- cut: gives true
}