rest_sanitize_array()
Converts the given value to an indexed array. If the conversion is not possible, it returns an empty array.
A non-indexed array will be turned into an indexed one.
Algorithm:
-
Checks if the given value is scalar (using the PHP function is_scalar()). If it is, it is processed by the function wp_parse_list() and the result is returned.
Scalar variables are variables with types int, float, string, and bool. Types array, object, and resource are not scalar.
-
If a non-scalar and non-array value (object, resource, etc.) is passed, the function will return an empty array.
- If an array is passed, the function will collect its values into an indexed array and return it.
Uses: wp_parse_list()
No Hooks.
Returns
Array. Array (empty or numbered).
Usage
rest_sanitize_array( $maybe_array );
- $maybe_array(mixed) (required)
- Value to convert.
Examples
#1 What the function returns
rest_sanitize_array( 'Vova,Misha,Timur,Dima' ); /* return Array ( [0] => Vova [1] => Misha [2] => Timur [3] => Dima ) */
rest_sanitize_array( [ 'name' => 'Olga', 'age' => 5 ] ); /* return Array ( [0] => Olga [1] => 5 ) */
Changelog
| Since 5.5.0 | Introduced. |
rest_sanitize_array() rest sanitize array code WP 6.9.1
function rest_sanitize_array( $maybe_array ) {
if ( is_scalar( $maybe_array ) ) {
return wp_parse_list( $maybe_array );
}
if ( ! is_array( $maybe_array ) ) {
return array();
}
// Normalize to numeric array so nothing unexpected is in the keys.
return array_values( $maybe_array );
}