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.

Ruslan Osmanov
  • 20,486
  • 7
  • 46
  • 60
Parvinder Singh
  • 81
  • 1
  • 10

4 Answers4

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

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

Beginner
  • 4,118
  • 3
  • 17
  • 26
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?

Panda
  • 6,955
  • 6
  • 40
  • 55
SOFe
  • 7,867
  • 4
  • 33
  • 61
0

Try ternary operator like this......

$ref= $row["ref"] ?$row["ref"]: "UnKnown";
echo $ref;
Hikmat Sijapati
  • 6,869
  • 1
  • 9
  • 19