Send form data by array to PHP

Asked

Viewed 3,064 times

2

Due to a system need 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 if I select only one, it brings the reported result and the other blank. And the Count of the array always returns 3:

Teste DIEGO . Fim
Teste . Fim
Teste . Fim

How could I treat the array to only have the data actually informed? I display it this way (by testing):

foreach( $name as $key => $n ) {
  print "Teste ".$n.". Fim<br>";
}
  • use empty() inside the foreach.

  • Can you show me?

  • 1

    if(!empty($n)){echo $n .'<br>'}else{ echo 'valor em branco';} I believe that’s it.

  • I believe that if you do so it works: foreach($name as $key => $n){ if($name[$key] == ""){ unset($name[$key) ; }

  • @rray, your answer worked, but Wallace Maxters got "better" because it comes straight in the post. Thanks!

1 answer

5


Use array_filter so that php only brings data that is not empty.

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

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

}

See working on IDEONE

The function array_filter will filter the values of array, leaving only those that are not empty. This function treats each value of the array in the same way as the function empty. 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 set a callback function to array_filter. If the expression returns true for the argument value, the item will remain. Otherwise, it will be removed from array.

Behold:

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

the result will be:

[1, 0]

  • 2

    The @rray response worked as well, but I think yours got more "correct". Thank you.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.