Code Modernization: Simplify isset() guards that initialize empty arrays.
Covering one recognizable idiom: initializing a container to an empty array before writing into it.
-if ( ! isset( $widget_options[ $widget_id ] ) ) {
- $widget_options[ $widget_id ] = array();
-}
+$widget_options[ $widget_id ] ??= array();
Every one of the 54 changed guards is an isset() check whose entire body is a single = array(); assignment to the tested expression. Each one is handled by one of four rules, so no case needs individual judgement:
- Convert the guard to
??= (35 places).
- Collapse nested guard chains to the deepest key, since
??= autovivifies missing parent arrays (add_meta_box(), remove_meta_box()):
$wp_meta_boxes[ $page ][ $context ] ??= array();
- Remove the guard where the next statement writes into the same array or property anyway, since that write creates it (9 places):
-if ( ! isset( $object_terms[ $id ] ) ) {
- $object_terms[ $id ] = array();
-}
$object_terms[ $id ][ $taxonomy ] = array();
- Inline the default where the next statement reassigns the same expression from an
array_merge() call (3 places):
$this->headers[ $key ] = array_merge( $this->headers[ $key ] ?? array(), $value );
Why this is safe
??= requires PHP 7.4, which is already the minimum supported version.
??=, ?? and ! isset() test the same condition, so the default is used in exactly the same cases.
- Only blocks whose body is a single assignment were changed. Any guard containing further statements was skipped, since
??= would let those statements run unconditionally.
- Removed guards are only those directly followed by a write into the same array, or into a property of a
stdClass object, where PHP creates the missing container the same way.
- No behavior change.
Developed in https://github.com/WordPress/wordpress-develop/pull/12912.
Props Soean, mukesh27, westonruter.
See #65823.