Get post array values

I have a form that sends all the data using jQuery .serialize()In Form Four, arrays qty[], etcit sends the form data to the sendMail page, and I want the output to be returned from arrays.

I tried:

$qty = $_POST['qty[]'];
foreach($qty as $value)
{
  $qtyOut = $value . "<br>";
}

And tried this:

for($q=0;$q<=$qty;$q++)
{
 $qtyOut = $q . "<br>";
}

Is this the right approach?

+5
source share
5 answers

You have []inside your variable $_POST- this is not required. You should use:

$qty = $_POST['qty'];

Then your code will look like this:

$qty = $_POST['qty'];

foreach($qty as $value) {

   $qtyOut = $value . "<br>";

}
+11
source

php automatically detects $ _ POST and $ _ GET arra so you can juse:

<form method="post">
    <input value="user1"  name="qty[]" type="checkbox">
    <input value="user2"  name="qty[]" type="checkbox">
    <input type="submit">
</form>

<?php
$qty = $_POST['qty'];

$qty php-. :

if (is_array($qty))
{
  for ($i=0;$i<size($qty);$i++)
  {
    print ($qty[$i]);
  }
}
?>

, :

print_r($_POST['qty']);

print_r($_POST);

, .

+7

My version of PHP 4.4.4 throws an error: Fatal error: call to undefined function: size ()

I changed the size to count, and then the procedure was correct.

<?php
$qty = $_POST['qty'];

if (is_array($qty)) {
   for ($i=0;$i<count($qty);$i++)
   {
       print ($qty[$i]);
   }
}
?>
+1
source

PHP handles nested arrays fine

to try:

foreach($_POST['qty'] as $qty){
   echo $qty
}
0
source

I prefer foreach insted for, because you do not need to adjust the size.

if( isset( $_POST['qty'] ) )
{
    $qty = $_POST ['qty'] ;
    if( is_array( $qty ) )
    {
        foreach ( $qty as $key => $value ) 
        {
            print( $value );
        }
    }
}
0
source

Source: https://habr.com/ru/post/1526712/


All Articles