wp_recursive_ksort()WP 6.0.0

Sorts an array and all nested arrays by key in ascending order (a-z).

Recursively applies the function ksort() to the array and all nested arrays.

If the value of the array is not an array, it will remain untouched.

No Hooks.

Returns

null. Nothing.

Usage

wp_recursive_ksort( $array );
$array(array) (required) (passed by reference — &)
The array to sort.

Examples

0

#1 Demo

Sort the array and all its sub-arrays by keys in alphabetical order:

$array = [
	'two' => 2,
	'one' => [
		'two' => 2,
		'one' => [
			'two' => 2,
			'one' => 1,
		],
	],
];

wp_recursive_ksort( $array );

print_r( $array );

/*
Array
(
	[one] => Array
		(
			[one] => Array
				(
					[one] => 1
					[two] => 2
				)

			[two] => 2
		)

	[two] => 2
)
*/

Changelog

Since 6.0.0 Introduced.

wp_recursive_ksort() code WP 6.9

function wp_recursive_ksort( &$input_array ) {
	foreach ( $input_array as &$value ) {
		if ( is_array( $value ) ) {
			wp_recursive_ksort( $value );
		}
	}

	ksort( $input_array );
}