Send form data by array to PHP

2

Due to a need of the system we are working on, I need to send 3 fields as an array to a PHP. Example:

<input type="text" name="name[]" />

<input type="text" name="name[]" />

<input type="text" name="name[]" />

What happens is that even though I select only one, it brings the result informed and the others blank. And the count of the array always returns 3:

Teste DIEGO . Fim
Teste . Fim
Teste . Fim

How could you handle the array only having the data actually entered? I display it this way (testing):

foreach( $name as $key => $n ) {
  print "Teste ".$n.". Fim<br>";
}
    
asked by anonymous 31.08.2016 / 22:37

1 answer

5

Use array_filter so php will only bring only non-blank data.

$names = array_filter($_POST['names']);

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

}

See working at IDEONE

The array_filter function will filter the values of array , leaving only those that are not empty. This function treats each value of array in the same way as the empty function. Values such as 0 , '0' , '' , array() (empty array) or false will be removed from array .

If the above behavior is not what you want, you can still define a callback function for array_filter . If the expression returns true to the value of the argument, the item will remain. Otherwise, it will be removed from array .

See:

array_filter([1, 0, ''], function ($value) {
     return $value !== '';
});

the result will be:

  

[1, 0]

    
31.08.2016 / 22:41