To mimick Javascript, I tried this in PHP:
$what == '3' ? ( $tot1 += $sum ; $nLinesProd++ ; )
: ( $tot2 += $sum ; $nLinesExp++; ) ;
I also tried {}
instead of ()
. Neither will work.
Is there a way to use the ternary operator the same way as I do in Javascript?
Ternary operator are meant for simple and single expression. If you want to write complex and compound statements then use of if
else
is promoted. But any how if you want to perform this step in ternary operation then you have to write the compound statements in functional block and call them in ternary operator.
<?php
$do = ($what=='3') ? prod() : exp();
function prod() {
$tot1 += $sum;
$nLinesProd++ ;
}
function exp() {
$tot2 += $sum;
$nLinesExp++;
}