Atara
Atara

Reputation: 3569

PHP: How to concatenate NULL to string

suddenly my site show new warning -

The relevant code:

printf ("<input type='text' name='C_Comment' value='" . $myComment . "'  >");

The warning I get:

probably because $myComment is null.

  1. I know I Can fix it if I first test if the value is null, and only then conctenate it. but is there a simpler way?

  2. Why did not I get this warning before?

Thanks,

Atara

EDIT: sorry, wrong title. The problem was that $myComment was not NULL, it contained special character.

Upvotes: 0

Views: 3717

Answers (4)

Artefacto
Artefacto

Reputation: 97835

No, you get that warning because you don't give enough arguments to printf; probably $myComment contained printf placeholders like %s.

Use echo instead if you don't want to use printf's formatting. You can also rewrite your printf call:

printf ("<input type='text' name='C_Comment' value='%s'>",
    $myComment);

Make sure you've escaped special chars in $myComment (see htmlspecialchars).

Upvotes: 6

imkingdavid
imkingdavid

Reputation: 1389

printf is a function used for formatting a string with given values. You have only supplied one argument to the function, so it is throwing that error in your face.

If you simply wish to print the text on the page, use echo (or just remove the f and use print) with the current string. Or you can do this:

printf("<input type='text' name='C_Comment' value='%s' />", $my_comment);

Here's the PHP.net Docs page for printf(), and you can also view related functions in the See Also section.

Upvotes: 1

Bas Slagter
Bas Slagter

Reputation: 9929

Add this before the prinf call if you have a default value (which is not empty):

$myComment = ($myComment == null) ? 'yourdefaultvalue' : $myComment;

Of course, an echo would do fine also (and than an empty value is no issue anymore):

<input type="text" name="C_Comment" value="<?=myComment?>" />

Upvotes: -1

hsz
hsz

Reputation: 152216

Instead of using printf just use echo:

echo "<input type='text' name='C_Comment' value='" . $myComment . "'  >";

Upvotes: 4

Related Questions