Make WordPress Core


Ignore:
Timestamp:
11/06/2026 07:34:18 PM (3 days ago)
Author:
SergeyBiryukov
Message:

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:

  1. Convert the guard to ??= (35 places).
  2. 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();
    
  3. 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();
    
  4. 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.

File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/src/wp-includes/general-template.php

    r65281 r65317  
    52015201        global $_wp_admin_css_colors;
    52025202
    5203         if ( ! isset( $_wp_admin_css_colors ) ) {
    5204                 $_wp_admin_css_colors = array();
    5205         }
     5203        $_wp_admin_css_colors ??= array();
    52065204
    52075205        $_wp_admin_css_colors[ $key ] = (object) array(
Note: See TracChangeset for help on using the changeset viewer.