John Davidson

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

0 comments
Message:


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.



My Answer:
) {
if ( is_array( $value ) ) {
return array_map( 'cstm_sanitize_array_data', $value, array_fill( 0, count( $value ), $override_is_string ) );
} else {
if ( $override_is_string ) {
return sanitize_text_field( $value );
} else {
return sanitize_text_field( $value );
}
}
} else {
return sanitize_text_field( $value );
}
}

In this function, I want to be able to pass a second parameter $override_is_string to the array_map function so that I can specify whether the data should be sanitized as a text field regardless of its type. However, array_map does not allow for passing additional parameters to the callback function.

One workaround for this limitation is to use a closure function instead of a regular function as the callback for array_map. This way, you can capture the additional parameter in the closure and pass it to the actual sanitize function:

$override_is_string = true;
$sanitize_callback = function( $value ) use ( $override_is_string ) {
return cstm_sanitize_array_data( $value, $override_is_string );
};

$sanitized_data = array_map( $sanitize_callback, $data );

This way, you can effectively pass additional parameters to the callback function used in array_map.

Rate this post

4 of 5 based on 8054 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us