开发者

PHP code syntax

Im trying to insert an inline开发者_如何学JAVA 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


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';


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


Try

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


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 :.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜