r/PHPhelp • • Nov 16 '20

Correct placeholder for NULL?

If I were to use a sprintf type of function where i would use %s for strings (for example), what would I use if I need to pass NULL?

7 Upvotes

11 comments sorted by

5

u/mrunkel Nov 16 '20

Feel free to ignore, but I would answer your question with another question.

When would it be appropriate to output NULL? Said another way, why would you ever need to print something out that is NULL?

This seems to be a code smell for me. If the underlying data is NULL, it probably shouldn't be printed.

1

u/PursuitOfAdvice Nov 17 '20

It's for a prepared sql statement

1

u/richardathome Nov 16 '20

Logging to a text file?

3

u/bkdotcom Nov 16 '20

print_r($val, true)

2

u/bkdotcom Nov 16 '20

How are you wanting null to be output?
'', "0", "0.0", or other?
what version of php?

sprintf('%s', null ?? 'NULL');

1

u/PursuitOfAdvice Nov 21 '20

I'm actually looking to import it into a mysql database, and it's auto increment primary key.

When I test the insert in phpmyadmin, I see it used null for the primary column.

So I'm asking to see how I'd represent null in the sql insert statement.

7

u/enos86 Nov 16 '20

The PHP docs for this function contain a note about this:

Variables will be co-erced to a suitable type for the specifier:

...and then it goes on to list all specifiers. None of them are null-sensitive -- they all will silently convert their input value into whatever type they want. The null value will thus be cast to the empty string, to 0, or to 0.0.

If you really need to display a nullable value and you want to do it yourself, your best bet might to use a conditional:

$number = 3.14;  // or maybe null
$formattedNumber = ($number !== null) ? sprintf('%1.1f', $number) : 'NULL';

(For strings, something like $value ?? 'null' might be enough. Of course then you cannot distinguish the null value and the "null" string anymore. It really depends on your use case.)

If you're using this for debugging, check out symfony/var-dumper instead of building it yourself!

1

u/crazedizzled Nov 16 '20

A string is by definition not null.

1

u/bkdotcom Nov 16 '20

It appears OP is aware of that.

1

u/crazedizzled Nov 16 '20

Then I'm not sure why he posted a question about it. You cannot have a string and null at the same time.

1

u/bkdotcom Nov 16 '20

sprintf : Returns a string produced according to the formatting string format.

There are format specifiers for handling integers and floats (not strings by definition) in various ways (binary, char-code, octal, string-representation).

OP wants to know the best way to handle/format null.