Search code examples
phpline-breaks

PHP Line Break not working


I am learning php and am making a statement that proves the local variable cannot be called outside a function where it is defined.

I can't seem to get a line break come out in the statement but only a line space.

<html>
<head>
<title>Testing Global and Local Variables</title>
</head>
<body>

<?php 

//Global varaible called after function
$g_test_string="this is the value in the variable outside the function at a global level!";

function printstring()
{
$l_test_string="this is the value of the variable inside the function at a local level!";
print($l_test_string);
}

//Calling statements

printstring();
echo "\r";
echo 'Global variable value: ' . $g_test_string;
echo 'Local variable value: ' . $l_test_string;

?>

</body>
</html>

The print out looks like this:

this is the value of the variable inside the function at a local level! Global variable value: this is the value in the variable outside the function at a global level! Local variable value:

I tried a break between the function call and echo for global variable but only produces a line space not a break.

Got to be something simple I imagine.

Many thanks

Andrew


Solution

  • If you want to be sure your line break is cross platform compatible, use PHP_EOL I usually use "\n". If you want the linebreak to appear in HTML, use "<br>".

    Edit in response to comments: Here's how you pull as much PHP out of the HTML as possible.

    <?php 
    
    //Global varaible called after function
    $g_test_string="this is the value in the variable outside the function at a global level!";
    ?>
    <html>
    <head>
    <title>Testing Global and Local Variables</title>
    </head>
    <body>
    <?php
    //Calling statements
    
    printstring();
    echo "<br>\n";
    echo 'Global variable value: ' . $g_test_string."<br>\n";
    
    echo 'Local variable value: ' . $l_test_string."<br>\n";
    ?>    
    </body>
    </html>
    
    <?php
      function printstring()
      {
        $l_test_string="this is the value of the variable inside the function at a local level!";
        print($l_test_string);
      }