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.

0

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

3 Comments

Are you sure the statement is correct? Seems to be faulty to me :/
yes, it's considered correct you can see in the array_map docs in php manual
My IDE means that the code is not complete - maybe my issue. I'll see.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.