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:29

$_POST is an array in itsself you don't need to make an array out of it. What you did is nest the $_POST array inside a new array. This is why you print Array. Change it to:

foreach ($_POST as $key => $value) {

  echo "<p>".$key."</p>";
  echo "<p>".$value."</p>";
  echo "<hr />";

} 
查看更多
做个烂人
3楼-- · 2020-02-26 09:32

Came across this 'implode' recently.

May be useful to output arrays. http://in2.php.net/implode

echo 'Variables: ' . implode( ', ', $_POST);
查看更多
霸刀☆藐视天下
4楼-- · 2020-02-26 09:33

Just:

foreach ( $_POST as $key => $value) {

  echo "<p>".$key."</p>";
  echo "<p>".$value."</p>";
  echo "<hr />";

} 
查看更多
倾城 Initia
5楼-- · 2020-02-26 09:34

$_POST is already an array, so you don't need to wrap array() around it.

Try this instead:

<?php 

 for ($i=0;$i<count($_POST['id']);$i++) {

  echo "<p>".$_POST['id'][$i]."</p>";
  echo "<p>".$_POST['value'][$i]."</p>";
  echo "<hr />";

} 

 ?>

NOTE: This works because your id and value arrays are symmetrical. If they had different numbers of elements then you'd need to take a different approach.

查看更多
做个烂人
6楼-- · 2020-02-26 09:42
<?php 

 foreach ($_POST as $key => $value) {
  echo '<p>'.$key.'</p>';
  foreach($value as $k => $v)
  {
  echo '<p>'.$k.'</p>';
  echo '<p>'.$v.'</p>';
  echo '<hr />';
  }

} 

 ?>

this will work, your first solution is trying to print array, because your value is an array.

查看更多
成全新的幸福
7楼-- · 2020-02-26 09:42

You are adding the $_POST array as the first element to $myarray. If you wish to reference it, just do:

$myarray = $_POST;

However, this is probably not necessary, as you can just call it via $_POST in your script.

查看更多
登录 后发表回答