1

I've come up with this SO question which nearly describes my question:

Array_map function in php with parameter

For me, I need to pass a second parameter to a custom sanitize array data function which tells the function to only sanitize as a text field - even it's numeric:

function cstm_sanitize_array_data( $value, bool $override_is_string = false ) 
    if ( empty( $value ) ) {
        return $value;
    }

    $value = wp_unslash( $value );

    if ( ! $override_is_string && is_numeric( $value ) ) {
        $value = absint( $value );
    }

    if ( $override_is_string || is_string( $value ) ) {
        error_log( 'Override: ' . $override_is_string );
        $value = sanitize_text_field( $value );
    }

    return $value;
}

When I call my function this way:

$sorted_product_ids = array_map( 'cstm_sanitize_array_data', $_POST['sorted_product_ids'] ?? null, [ true ] );

I can see that the first error logging is true and all the next ones are false. This results in the fact that my values like 015 are stripped and results in 15 only because the absint() function completely makes sure, that it's a valid number. So somehow my $override_is_string param is only set once and is totally ignored after the first iteration.

Dharman
  • 30,962
  • 25
  • 85
  • 135
Mr. Jo
  • 4,946
  • 6
  • 41
  • 100

1 Answers1

1

The problem is that the $override_is_string is iterate at once internally because the supplementary array has only 1 count so that $override_is_stringwill be false in the next iteration of the map, you can fix it by making array that same count with the sorted_product_ids

You may use array_fill to generate the array with value of true

$sorted_product_ids = array_map(
  'cstm_sanitize_array_data', 
   $_POST['sorted_product_ids'] ?? [], 
   array_fill(0,count($_POST['sorted_product_ids'] ?? [],true)
);

You may see this fiddle or this fiddle

Jerson
  • 1,700
  • 2
  • 10
  • 14