WordPress.org

Make WordPress Core

Changeset 50958


Ignore:
Timestamp:
05/24/2021 08:29:03 AM (5 months ago)
Author:
youknowriad
Message:

General: Add _wp_array_set function.

This adds the _wp_array_set function, which is the counterpart of the existing _wp_array_get.
This utility is to be used by the Global Settings work.

Props nosolosw, jorgefilipecosta.
See #53175.

Location:
trunk
Files:
1 added
1 edited

Legend:

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

    r50822 r50958  
    46284628
    46294629/**
     4630 * Sets an array in depth based on a path of keys.
     4631 *
     4632 * It is the PHP equivalent of JavaScript's `lodash.set()` and mirroring it may help other components
     4633 * retain some symmetry between client and server implementations.
     4634 *
     4635 * Example usage:
     4636 *
     4637 *     $array = array();
     4638 *     _wp_array_set( $array, array( 'a', 'b', 'c', 1 );
     4639 *     $array becomes:
     4640 *     array(
     4641 *         'a' => array(
     4642 *             'b' => array(
     4643 *                 'c' => 1,
     4644 *             ),
     4645 *         ),
     4646 *     );
     4647 *
     4648 * @param array $array   An array that we want to mutate to include a specific value in a path.
     4649 * @param array $path    An array of keys describing the path that we want to mutate.
     4650 * @param mixed $value   The value that will be set.
     4651 */
     4652function _wp_array_set( &$array, $path, $value = null ) {
     4653    // Confirm $array is valid.
     4654    if ( ! is_array( $array ) ) {
     4655        return;
     4656    }
     4657
     4658    // Confirm $path is valid.
     4659    if ( ! is_array( $path ) ) {
     4660        return;
     4661    }
     4662    $path_length = count( $path );
     4663    if ( 0 === $path_length ) {
     4664        return;
     4665    }
     4666    foreach ( $path as $path_element ) {
     4667        if (
     4668            ! is_string( $path_element ) && ! is_integer( $path_element ) &&
     4669            ! is_null( $path_element )
     4670        ) {
     4671            return;
     4672        }
     4673    }
     4674
     4675    for ( $i = 0; $i < $path_length - 1; ++$i ) {
     4676        $path_element = $path[ $i ];
     4677        if (
     4678            ! array_key_exists( $path_element, $array ) ||
     4679            ! is_array( $array[ $path_element ] )
     4680        ) {
     4681            $array[ $path_element ] = array();
     4682        }
     4683        $array = &$array[ $path_element ]; // phpcs:ignore VariableAnalysis.CodeAnalysis.VariableAnalysis.VariableRedeclaration
     4684    }
     4685    $array[ $path[ $i ] ] = $value;
     4686}
     4687
     4688/**
    46304689 * Determines if the variable is a numeric-indexed array.
    46314690 *
Note: See TracChangeset for help on using the changeset viewer.