1

I get some data from MySQL, and I print the data as echo $row['ref'];.

Sometimes echo $row['ref']; returns empty result. I want to compose a condition like echo isset($row['ref']) ? $row['ref']:'Unknown'; which will show Unknown word if echo $row['ref']; returns empty result.

Thanks in advance.

3
  • 1
    And what's wrong with the isset?: code you mentioned? Commented Dec 18, 2016 at 9:13
  • But it does not display unknown word Commented Dec 18, 2016 at 9:14
  • 2
    use empty instead of isset the php function empty will check if the variable exist and is not empty Commented Dec 18, 2016 at 9:28

4 Answers 4

1

As you mention in your scenario which

isset($row['ref']) ? $row['ref']:'UnKnown';

you stated that you receive an empty value even you use isset which mean $row['ref'] exist but it is empty

use empty instead of isset the php function empty will check if the variable exist and is not empty

This will prevent you from having an empty value for your variable $ref

$ref= (!empty($row["ref"])) ?$row["ref"]: "UnKnown";

Demo

Sign up to request clarification or add additional context in comments.

Comments

1

Perhaps 'ref' is present as an array key but has null as value.

<?php $row = array('ref' => null); echo (!empty($row['ref'])) ? $row['ref'] : 'UnKnown'; ?>

2 Comments

?? is only for non-null. It does not do what empty() does.
the empty function alone is enough
0

Try ternary operator like this......

$ref= $row["ref"] ?$row["ref"]: "UnKnown";
echo $ref;

Comments

0

If isset doesn't work, it might be that mysqli returns the result as an empty string.

You may want to use the ?: operator for quick if-false fallback:

echo $row["ref"] ?: "UnKnown";

See: How do I use shorthand if / else?

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.