Tribe__Utils__Array::set( mixed $array, string|array $key, mixed $value )
Set key/value within an array, can set a key nested inside of a multidimensional array.
Contents
Example: set( $a, [ 0, 1, 2 ], ‘hi’ ) sets $a[0][1][2] = ‘hi’ and returns $a.
Parameters
- $array
-
(mixed) (Required) The array containing the key this sets.
- $key
-
(string|array) (Required) To set a key nested multiple levels deep pass an array specifying each key in order as a value. Example: array( 'lvl1', 'lvl2', 'lvl3' );
- $value
-
(mixed) (Required) The value.
Return
(array) Full array with the key set to the specified value.
Source
File: src/Tribe/Utils/Array.php
public static function set( array $array, $key, $value ) { // Convert strings and such to array. $key = (array) $key; // Setup a pointer that we can point to the key specified. $key_pointer = &$array; // Iterate through every key, setting the pointer one level deeper each time. foreach ( $key as $i ) { // Ensure current array depth can have children set. if ( ! is_array( $key_pointer ) ) { // $key_pointer is set but is not an array. Converting it to an array // would likely lead to unexpected problems for whatever first set it. $error = sprintf( 'Attempted to set $array[%1$s] but %2$s is already set and is not an array.', implode( $key, '][' ), $i ); _doing_it_wrong( __FUNCTION__, esc_html( $error ), '4.3' ); break; } elseif ( ! isset( $key_pointer[ $i ] ) ) { $key_pointer[ $i ] = array(); } // Dive one level deeper into the nested array. $key_pointer = &$key_pointer[ $i ]; } // Set the value for the specified key $key_pointer = $value; return $array; }