I have a variable set of identical input fields in my form where some can be empty.
<input type="text" class="form-control" name="option[]" placeholder="fill in" />
<input type="text" class="form-control" name="option[]" placeholder="optional" />
<input type="text" class="form-control" name="option[]" placeholder="optional" />
the values of these input fields come into the array $_POST["option"]
I want to filter $_POST["option"]
and for that I am using the following code:
$filter = array("option" => array("filter"=>FILTER_CALLBACK,"flags"=>FILTER_FORCE_ARRAY,"options"=>"ucwords"));
$optionfin = filter_input_array(INPUT_POST, $filter);
But now I want to also use the array_filter
function to remove the empty fields so I can INPUT only the filled in fields into my database but this doesn't seem to work.
$option = array_filter($optionfin);
when I do the following:
$optionfin = array_filter($_POST["option"]);
this is working fine, but i know you better not access the $_POST
this way because it isn't that safe...
Can anyone help me to point out where i am going wrong?
Thanks
Because you are using filter_input_array
, you will actually end up with an associative array that corresponds to $_POST
. So to filter out empty fields as you are trying to do, you will need to specify the option
key:
$option = array_filter($optionfin['option']);