1

This is not the first time I encountered the problem. I have 2 variables in PHP of type string. When both of them are not empty I want something like this :

 echo $var1 . ', ' . $var2;

My problem is that sometimes $var1 or $var2 could be empty so the coma is floating. I try this :

 echo $var1 && $var2 ? $var1 . ', ' . $var2 : $var1 || $var2;

But when we are in the right condition, it send 1. I hope the only way is not to test $var1 && $var2 then test $var1 and then test $var2.

Thanks in advance,

chles
  • 175
  • 1
  • 1
  • 11
  • 1
    Possible duplicate of [if statement in the middle of concatenation?](https://stackoverflow.com/questions/13089747/if-statement-in-the-middle-of-concatenation) – Markus Safar Dec 03 '18 at 15:19
  • 1
    Unlike some languages, PHP's `||` operator just returns a boolean, not which of the two variables satisfied the test – iainn Dec 03 '18 at 15:19
  • what do you want to actually display ? $var1 . ', ' . $var2 if both are not empty and the one which is not empty if the other is empty ? something else ? – RomMer Dec 03 '18 at 15:22
  • `IF (in_doubt) { do_it_longhand(); ) {` – RiggsFolly Dec 03 '18 at 15:22

4 Answers4

10
echo join(', ', array_filter([$var1, $var2]));

array_filter removes all empty values, and join puts the joiner between the remaining items, if there are more than one.

deceze
  • 510,633
  • 85
  • 743
  • 889
1

You can do it by many way e.g by checking empty, using ternary and so on but I've one way to fix this using array_filter() to remove empty values and implode with , . Then it'll not floating when any of the variable is empty string and it can consume multiple variables. Hope this helps :)

<?php
 $implode = ',&nbsp;';
 $var1 = 'xyz';
 $var2 = '';
 $result = [$var1,$var2];
 $filtered_result = array_filter($result);
 echo implode($implode,$filtered_result);
?>

DEMO: https://3v4l.org/PZ8Rv

A l w a y s S u n n y
  • 36,497
  • 8
  • 60
  • 103
0

try this

if(!(empty($var1) && empty($var2))){
echo $var1 . ',&nbsp;'.$var2;
}else{
$value = !empty($var1)? $var1 : (!empty($var2)? $var2 : "both are empty");
echo $value
}
0

your right condition use || operator which returns a boolean. if the right statement or left statement is true it will return true (1), or it will return false (0)

then you have to do something like this

 echo ($var1 && $var2 ? $var1 . ',&nbsp;' . $var2 : ($var1 ? $var1 : $var2));

note that $var1 has to be defined (null or empty but it has to be defined)

RomMer
  • 113
  • 12