3

What is the correct way to use an IF/ELSE statement inside of a variable string?

Example:

$htmlOutput = 'The current color of the sky is ' . 
if ($time==="day") { . 'blue.' . } 
else if ($time==="night") { . 'black' . };

Obviously that example does not work, but you see what I'm trying to do. I know I could just continue the variable inside of the if statement like:

$htmlOutput .= '';

but I'm curious if there's a way to do it as stated above.

2
  • 2
    Yep, with a ternary operator Commented Nov 7, 2014 at 19:07
  • Avoid temptations to do anything more complex than a single if x then y else z in a ternary operation though. They can be nested but it quickly becomes very unreadable. (if x then (if a then b else c) else z) Commented Nov 7, 2014 at 19:10

3 Answers 3

7

You could use a ternary operator like this

$htmlOutput = 'The current color of the sky is ' . ($time == 'day' ? 'blue' : 'black');
Sign up to request clarification or add additional context in comments.

1 Comment

That's perfect, thanks! And thanks to all who answered so fast.
2

use ternary operator instead of if else

 $htmlOutput = 'The current color of the sky is ' . ($time==="day") ?'blue':($time==="night")?'black':'';

or more simpler is to

   $htmlOutput = 'The current color of the sky is ' . ($time==="day") ?'blue':'black';

3 Comments

The first one looks funky. It's either got an extra ? or a missing :.
it is used for else if , multiple operational statement
Yes, but it is not valid syntax. Second one looks good though.
1

This should work for you:

<?php


    $time = "night";

    $htmlOutput = 'The current color of the sky is ' . ($time === 'day' ? 'blue' : 'black');

    echo $htmlOutput;


?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.