How to print_r $_POST array?

2020-02-26 08:54发布

I have following table.

<form method="post" action="test.php">
  <input name="id[]" type="text" value="ID1" />
  <input name="value[]" type="text" value="Value1" />
  <hr />

  <input name="id[]" type="text" value="ID2" />
  <input name="value[]" type="text" value="Value2" />
  <hr />

  <input name="id[]" type="text" value="ID3" />
  <input name="value[]" type="text" value="Value3" />
  <hr />

  <input name="id[]" type="text" value="ID4" />
  <input name="value[]" type="text" value="Value4" />
  <hr />

  <input type="submit" />
</form>

And test.php file

<?php 

  $myarray = array( $_POST);
  foreach ($myarray as $key => $value)
  {
    echo "<p>".$key."</p>";
    echo "<p>".$value."</p>";
    echo "<hr />";
  }

?>

But it is only returning this: <p>0</p><p>Array</p><hr />

What I'm doing wrong?

10条回答
霸刀☆藐视天下
2楼-- · 2020-02-26 09:45

The foreach loops work just fine, but you can also simply

print_r($_POST);

Or for pretty printing in a browser:

echo "<pre>";
print_r($_POST);
echo "</pre>";
查看更多
疯言疯语
3楼-- · 2020-02-26 09:45

Because you have nested arrays, then I actually recommend a recursive approach:

function recurse_into_array( $in, $tabs = "" )
{
    foreach( $in as $key => $item )
    {
        echo $tabs . $key . ' => ';
        if( is_array( $item ) )
        {
            recurse_into_array( $item, $tabs . "\t" );
        }
        else
        {
            echo $tabs . "\t" . $key;
        }
    }
}

recurse_into_array( $_POST );
查看更多
干净又极端
4楼-- · 2020-02-26 09:47

$_POST is already an array. Try this:

foreach ($_POST as $key => $value) {
    echo "<p>".$key."</p>";
    echo "<p>".$value."</p>";
    echo "<hr />";
} 
查看更多
ゆ 、 Hurt°
5楼-- · 2020-02-26 09:50

Why are you wrapping the $_POST array in an array?

You can access your "id" and "value" arrays using the following

// assuming the appropriate isset() checks for $_POST['id'] and $_POST['value']

$ids = $_POST['id'];
$values = $_POST['value'];

foreach ($ids as $idx => $id) {
    // ...
}

foreach ($values as $idx => $value) {
    // ...
}
查看更多
登录 后发表回答