PHP:<pre> tag not working with print_r

时间:2017-11-10 11:15:08

标签: php html tags pre

I've two code snippets. In first code snippet the <pre></pre> tag doesn't work while in second it works. Why so? Where I'm making a mistake in first code snippet?

Code Snippet 1 Here it doesn't work

      <?php
        $arr1 = array(2, 3);
        $arr2 = $arr1;
        $arr2[] = 4; // $arr2 is changed,
                     // $arr1 is still array(2, 3)

        $arr3 = &$arr1;
        $arr3[] = 4; // now $arr1 and $arr3 are the same

        echo "arr1 : "."<pre>".print_r($arr1)."</pre><br>";
        echo "arr2 : "."<pre>".print_r($arr2)."</pre><br>";
        echo "arr3 : "."<pre>".print_r($arr3)."</pre><br>"; 
    ?>

Code Snippet 2 Here it works

    <?php
      if ($_POST) {
        echo '<pre>';
        echo htmlspecialchars(print_r($_POST, true));
        echo '</pre>';
      }
    ?>
    <form action="" method="post">
        Name:  <input type="text" name="personal[name]" /><br />
        Email: <input type="text" name="personal[email]" /><br />
        Beer: <br />
        <select multiple name="beer[]">
            <option value="warthog">Warthog</option>
            <option value="guinness">Guinness</option>
            <option value="stuttgarter">Stuttgarter Schwabenbräu</option>
        </select><br />
        <input type="submit" value="submit me!" />
    </form>

1 个答案:

答案 0 :(得分:1)

您的代码的问题是您将pre标记与print_r的输出连接起来,因此您的代码首先打印数组然后连接。

注意:您应该传递2nd参数true以获取字符串输出。

将此方式更改为:

echo "arr1 : <pre>".print_r($arr1)."</pre><br>";

:此:

echo "arr1 : <pre>".print_r($arr1,true)."</pre><br>";

echo "arr1 : <pre>";
print_r($arr1);
echo "</pre><br>";