rest_stabilize_value()WP 5.5.0

Unifies (standardizes) the passed value according to the semantics of the JSON schema.

The task of this function is to check the value and, if necessary, process it to bring it to a uniform appearance. This is needed so that the values can then be compared.

For example, we have two identical associative arrays. They differ only in the arrangement of elements. To compare them and ensure they are the same, this function needs to be used. See example 2.

Algorithm of the function:

  1. If a scalar or null is passed (is_scalar(), is_null()), it is not processed and returned as is.
  2. If an object is passed, it is also not processed and returned as is. However, the function _doing_it_wrong() is triggered with the message "Cannot stabilize objects. Convert the object to an array first.". That is, passing objects to the function is incorrect.
  3. If an array is passed, it and all nested arrays are recursively sorted by keys (see ksort()) and the new sorted (unified) array is returned back.

No Hooks.

Returns

Mixed. The passed value in a unified (standard) form.

Usage

rest_stabilize_value( $value );
$value(mixed) (required)

Value for unification. Must be sanitized.

An object cannot be passed - it is not processed. The object must be converted to an array before passing.

Examples

0

#1 Demo:

$fruits = [
	'd' => 'lemon',
	'a' => 'orange',
	'b' => 'banana',
	'c' => 'apple',
];

rest_stabilize_value( $fruits );

/* will return
Array (
	[a] => orange
	[b] => banana
	[c] => apple
	[d] => lemon
)
*/
$list = [
	'fruits'     => [
		'lemon' => [
			5 => 'yellow',
			3 => 'sour',
		],
		'apple' => [
			'yellow',
			'red',
			'green',
		],
	],
	'vegetables' => [
		'potato' => [
			'ripe' => true,
			'gmos' => false,
		],
	],
];

rest_stabilize_value( $list );

/* will return
Array (
	[fruits] => Array (
		[apple] => Array (
			[0] => yellow
			[1] => red
			[2] => green
		)
		[lemon] => Array (
			[3] => sour
			[5] => yellow
		)
	)
	[vegetables] => Array (
		[potato] => Array (
			[gmos] => false
			[ripe] => true
		 )
	)
)
*/
0

#2 Comparison of two arrays: {#ex2}

$array1 = [
	'one' => 'one',
	'two' => 'two',
	'three' => 'three',
];

$array2 = [
	'two' => 'two',
	'one' => 'one',
	'three' => 'three',
];

var_dump( $array1 === $array2 ); // false

var_dump( rest_stabilize_value( $array1 ) === rest_stabilize_value( $array2 ) ); // true

Changelog

Since 5.5.0 Introduced.

rest_stabilize_value() code WP 6.9.1

function rest_stabilize_value( $value ) {
	if ( is_scalar( $value ) || is_null( $value ) ) {
		return $value;
	}

	if ( is_object( $value ) ) {
		_doing_it_wrong( __FUNCTION__, __( 'Cannot stabilize objects. Convert the object to an array first.' ), '5.5.0' );

		return $value;
	}

	ksort( $value );

	foreach ( $value as $k => $v ) {
		$value[ $k ] = rest_stabilize_value( $v );
	}

	return $value;
}