Maurice
Maurice

Reputation: 97

Why suddenly PHP adds the string 'null' to a string?

I suddenly have this strange behavior in PHP. I looked around here but cannot find a reasonable explanation

I have an extremely simple example:

<?php
   $test = 'hello123';
   print $test;
?>

This shows: hello123null in the webbrowser. When I echo instead of print the result, its the same. When I put the string in double quotes also the same.

No matter what I do, it always appends the string 'null' to it.

What is happening here?

Upvotes: 2

Views: 92

Answers (1)

Jairus
Jairus

Reputation: 846

When serving web pages and mixing HTML and PHP there are scenarios where you can flush hidden characters.

How to troubleshoot:

  1. Turn on show all characters in the IDE so you can see spaces, line breaks, etc.
  2. Verify no other pages are executed after that script. Sometimes when flipping between HTML and PHP extra characters are injected in the view if you are not following best practices.
  3. Put another print line after your print hello123, is it still after hello123 or your last command?

    ("hello123");
    print("test");
    
  4. Try obflush () to pin point issue: see https://www.php.net/manual/en/function.ob-flush.php

    print("hello123");
    ob_flush();
    flush();
    print("test");
    
  5. Lastly, try setting your header.

    header( 'Content-type: text/html; charset=utf-8' );

Upvotes: 1

Related Questions