سؤال

I am trying to create line breaks in my php script. I have variables using session, and I cannot figure out how to create line breaks with them. I have tried the following (as well as different combinations) as well as googling to try and find a solution with absolutely no luck at all.

 <?php

session_start();

$_SESSION['firstname'] = $_POST['firstname'];
$_SESSION['lastname'] = $_POST['lastname'];

echo nl2br("First Name : $_SESSION['firstname']\n\r");
echo nl2br("Last Name : $_SESSION['lastname']\n\r");
?>

I am grabbing variables from a form on a previous page. If I just echo the variables like so,

<?php

session_start();

$_SESSION['firstname'] = $_POST['firstname'];
$_SESSION['lastname'] = $_POST['lastname'];

echo $_SESSION['firstname'];
echo $_SESSION['lastname'];
?>

It works just fine. I am having a difficult time trying to find out how to use the syntax of nl2br (which I have also successfully used before) with session variables in php.

Any help is greatly appreciated. Thanks!

-Anthony

UPDATE: Answer below via Marc B. When session variables are in double-quotes, single-quotes must be removed.

<?php

session_start();

$_SESSION['firstname'] = $_POST['firstname'];
$_SESSION['lastname'] = $_POST['lastname'];

echo nl2br("First Name : $_SESSION[firstname]\n\r");
echo nl2br("Last Name : $_SESSION[lastname]\n\r");
?>
هل كانت مفيدة؟

المحلول

nl2br is a glorified remake of str_replace("\n", "<br />", $text). If your string doesn't have ANY newline characters, there's nothing to replace and you've basically got an expensive print/echo occuring.

You also have PHP syntax errors. You cannot use quoted array keys in a double-quoted string:

echo "$array[key]"; // ok
echo "$array['key']"; // wrong
echo "{$array['key']}"; // ok - extended syntax.

نصائح أخرى

echo nl2br("First Name" . $_SESSION['firstname'] . "\r\n");
echo nl2br("First Name" . $_SESSION['lastname'] . "\r\n");

Or could you try?

echo "First Name".$_SESSION['firstname']."<br />";
echo "Last Name".$_SESSION['lastname']."<br />";
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top