0

I know how to do something like this in Perl, but not sure how to do it the correct way in Php...

Say I have a string called: $string

What is the proper way to do this:

echo "Code is " . ($string || "Great");

So it would print $string to the browser, IF it had value, otherwise it would print "Great" to the browser.

do I have to use a if statement or is there a way to do it like this:

($string == "s1") ? 's2':'s1'

Sorry for my Php Ignorance :)

-Richard

1
  • 1
    The PHP way to do it is echo "Code is " . ($string ?: "Great"); Read about the conditional ternary operator. Commented Jan 30, 2016 at 22:09

2 Answers 2

1
echo "Code is " . (empty($string) ? "Great" : $string);
Sign up to request clarification or add additional context in comments.

1 Comment

that is what I was looking for. It worked. Thank you. :)
0

Use this to check if the string is set:

echo (isset($string) && $string !== '')? $string : "Great";

When only use empty a string which contains only '0' will be empty.

1 Comment

Overcomplicated. echo $string ?: "Great" does the job more straightforwardly.

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.