phparray-mapfilter-var

array_map and filter_var return unexpected results


I have the following code when submitting a form

$data['item_cost'] = ( isset( $_POST['item-cost'] ) ? array_map( "filter_var", array_filter( $_POST['item-cost'] ), array( FILTER_VALIDATE_FLOAT ) ) : "" );

but the result returns the first item as valid and the other items as false. Here's an example of the $_POST['item-cost'] value

array(3) {
  [0]=>
  string(4) "6.15"
  [1]=>
  string(4) "6.15"
  [2]=>
  string(4) "0.50"
}

and the resulting $data['item-cost'] value:

array(3) {
  [0]=>
  float(6.15)
  [1]=>
  bool(false)
  [2]=>
  bool(false)
}

I feel like I'm missing something obvious here? Thanks.


Solution

  • You've got this:

    array_map(
        "filter_var",
        array_filter($_POST['item-cost']),
        array(FILTER_VALIDATE_FLOAT)
    )
    

    This works for the first element because the third argument of array_map is consumed, one element per call to the callable. For your example to work, you'd need this:

    array_map(
        "filter_var",
        array_filter($_POST['item-cost']),
        array(FILTER_VALIDATE_FLOAT, FILTER_VALIDATE_FLOAT, FILTER_VALIDATE_FLOAT)
    )
    

    Which of course makes no sense for your use case. I'd recommend using an arrow function instead:

    array_map(
        fn($v) => filter_var($v, FILTER_VALIDATE_FLOAT),
        array_filter($_POST['item-cost'])
    )