-3

I want two things to happen when this is true. It's working fine, but i'm not sure is this good programming.

$a =1;  
($a == 1) ? (($b= 'val1') && ($c= 'val2')) : null;
echo $b . '<br/>';
echo $c;

I could simply write with if else but this way, it's smart. please help me...

Thilina
  • 117
  • 6
  • 1
    *"this way, it's smart"* - no, it's not... – DCoder May 23 '12 at 08:29
  • 4
    No, actually it's not smart; it's just showing off. Good for learning, but not good for real world code. You should use an `if`. – Jon May 23 '12 at 08:30
  • smart? i think it's more smarter is to write code so everyone easy understands. I would try avoid ternary operators, it confuses matters. – Aurimas Ličkus May 23 '12 at 08:31
  • 1
    I don't think this way is smart, smart code is clean code. – xdazz May 23 '12 at 08:31
  • possible duplicate of [To ternary or not to ternary?](http://stackoverflow.com/questions/160218/to-ternary-or-not-to-ternary) – Gordon May 23 '12 at 08:32

4 Answers4

1

Simple ...

<?php
$age = 20;
$status = ($age >= 18) ? "adult" : "kid";
echo $status;
?>
ThiefMaster
  • 310,957
  • 84
  • 592
  • 636
HamZa
  • 14,671
  • 11
  • 54
  • 75
1

It's bad. You should use if is this situation, it fits better.

Notice that mixing PHP and HTML in one file is bad. You must use template engine for this (Smarty, for example). Otherwise it can't be called good programming anyway.

Pavel Strakhov
  • 39,123
  • 5
  • 88
  • 127
1

Thats BAD style. NEVER should it be used in real code.

BTW. if you are keen on exploring, even this should work for you:

<?php
$a=1;
$a==1 && ($b='val1') && ($c='val2');
echo $b;
echo $c;
?>

That comes from Short-circuit evaluation.

UltraInstinct
  • 43,308
  • 12
  • 81
  • 104
  • $a =1; if($a == 1){ $b= 'val1'; $c= 'val2'; } this is what i want to do with that short hand code yes i could use this method without messing up but i just test it – Thilina May 23 '12 at 08:57
  • Your code is the recommended approach. Do not try something obfuscated. – UltraInstinct May 23 '12 at 09:11
-1

If the first condition matches, the second and the third will be evalued.

$a == 1 AND $b = 'val1' AND $c = 'val2';
flowfree
  • 16,356
  • 12
  • 52
  • 76