rest_stabilize_value()
Stabilizes a value following JSON Schema semantics.
For lists, order is preserved. For objects, properties are reordered alphabetically.
No Hooks.
Return
Mixed
. The stabilized value.
Usage
rest_stabilize_value( $value );
- $value(mixed) (required)
- The value to stabilize. Must already be sanitized. Objects should have been converted to arrays.
Examples
#1 Demo: [auto-translate]
$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 ) ) ) */
#2 Comparison of two arrays: {#ex2} [auto-translate]
$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() rest stabilize value code WP 6.8
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; }