wp_parse_id_list()
Processes/cleans an array of numbers (IDs) or a string where numbers are separated by commas or spaces. Will return an array of numbers.
The function splits the string into IDs and processes each ID: converts it into a number. In the end, duplicate IDs are removed from the resulting array.
Uses: wp_parse_list()
1 time — 0.000044 sec (very fast) | 50000 times — 0.53 sec (very fast)
No Hooks.
Returns
Int[]. Cleaned array with IDs (numbers).
Usage
wp_parse_id_list( $list );
- $list(array/string/number) (required)
- List of IDs. An array or string where numbers are separated by commas or spaces.
Examples
#1 Get the list of IDs from the string
Suppose a list of numbers (IDs) is passed to the function as a string. The numbers are separated by spaces, tabs or commas. We need to create an array of these numbers:
$str_ids = '1 2 , 3 4 5, 6'; $ids = wp_parse_id_list( $str_ids ); /* We get: Array ( [0] => 1 [1] => 2 [2] => 3 [3] => 4 [4] => 5 [5] => 6 ) */
#2 We get only the numbers from the array
Suppose we have a data array of numbers and strings and we only need to get numbers of it values:
$array = array( 1, '2', '2', 'foo', ' 3', '4foo', 05, 'bar', -6 ); $ids = wp_parse_id_list( $array ); /* We get: Array ( [0] => 1 [1] => 2 [3] => 0 [4] => 3 [5] => 4 [6] => 5 [8] => 6 )
#3 If pass only one number
$ids = wp_parse_id_list( 1 ); /* Array ( [0] => 1 ) */ $ids = wp_parse_id_list( '' ); // empty array []
Changelog
| Since 3.0.0 | Introduced. |
| Since 5.1.0 | Refactored to use wp_parse_list(). |
wp_parse_id_list() wp parse id list code WP 6.8.3
function wp_parse_id_list( $input_list ) {
$input_list = wp_parse_list( $input_list );
return array_unique( array_map( 'absint', $input_list ) );
}