简体   繁体   中英

Why can I not pass an additional parameter when using array_map within PHP?

I need some help: 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.

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_string will 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM