Conditional statment in the middle of output?

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
MattSharp
Forum Commoner
Posts: 62
Joined: Wed Apr 24, 2002 2:25 pm

Conditional statment in the middle of output?

Post by MattSharp »

Is it somehow possible to have an if statement in the middle of an echo. Like:

Code: Select all

echo "bill likes" . if ($likes =="yes") echo "me" . "!!!!!!"
I tried code similar to that without any luck. I wondered if there was a way to get around it or make it work. Cause there is a certain part in the code where I want to output something if an if statement is true and nothing if its false. Thanks.
hedge
Forum Contributor
Posts: 234
Joined: Fri Aug 30, 2002 10:19 am
Location: Calgary, AB, Canada

Post by hedge »

echo "bill likes" . (($likes=='yes') ? 'me' : '!!!!!!')
Jim
Forum Contributor
Posts: 238
Joined: Fri Apr 19, 2002 5:26 am
Location: Near Austin, Texas

Post by Jim »

You could also try a solution like this:

Code: Select all

<?
if($likes == 'yes') {
$answer = "me!";
} else {
$answer = '';
}

echo "Bill likes $answer";

?>
User avatar
twigletmac
Her Royal Site Adminness
Posts: 5371
Joined: Tue Apr 23, 2002 2:21 am
Location: Essex, UK

Post by twigletmac »

You could simplify:

Code: Select all

if($likes == 'yes') { 
$answer = "me!"; 
} else { 
$answer = ''; 
}
to a one-liner using the ternary operator like hedge had in his code:

Code: Select all

$answer = ($likes == 'yes') ? 'me!' : '';
Mac
Post Reply