0

Im trying to insert an inline if inside a print statement in PHP but I can't find the correct syntax.

What I'm trying to do is something like this:

$a = 1;
$b = 1;
print('pretext ' .($a == $b) ? 'texta' : 'textb'. ' posttext');

But it just prints texta when it should be printing pretext texta posttext

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356
David Espart
  • 11,520
  • 7
  • 36
  • 50
  • 1
    because there is less error prone and more readable solutions – Gordon Jan 07 '11 at 12:33
  • 1
    Then the comment should be "there are better ways to do it" (and maybe some explanation), no "just don't do it". That is a troll comment... – David Espart Jan 07 '11 at 12:38
  • You can find more Q&A about Ternary Operators in http://stackoverflow.com/questions/3737139/reference-what-does-this-symbol-mean-in-php – Gordon Jan 07 '11 at 12:43

4 Answers4

3
print('pretext ' . (($a == $b) ? 'texta' : 'textb') . ' posttext');
tdammers
  • 20,353
  • 1
  • 39
  • 56
3

Your code effectively means

print('pretext ' . ($a == $b) ? 'texta' : 'textbposttext');

You could do

print('pretext ' . (($a == $b) ? 'texta' : 'textb') . ' posttext');

But why not use printf to increase readability

printf(
    'pretext %s posttext',
    $a == $b ? 'texta' : 'textb'
);

or dont concatenate at all and send directly to stdout

echo 'pretext ',
     $a == $b ? 'texta ' : 'textb ',
     'posttext';
Gordon
  • 312,688
  • 75
  • 539
  • 559
2

Try

$a = 1;
$b = 1;
print('pretext ' . (($a == $b) ? 'texta' : 'textb' ) . ' posttext');
Jake N
  • 10,535
  • 11
  • 66
  • 112
2

The other answers here solve your problem so I'll offer an explanation with why your code isn't working.

The issue with your current code is its implied order of execution. It's being evaluated like this:

print ('pretext ' .($a == $b)) ? 'texta' : ('textb'. ' posttext')

You can see that 'pretext' is being concatenated with a boolean value (which, stringified, is either 1 or blank), and then checked. Since non-empty strings always evaluate to true (because of 'pretext'), you get 'texta'. Also notice that the last two strings are being concatenated as part of the expression after the :.

BoltClock
  • 700,868
  • 160
  • 1,392
  • 1,356