Created: 2017.04.12
Get the first key, the last key, the first value or the last value of a (hash) array
WordPress uses a hash array to populate select menus in the customizer:
$wp_customize->add_control('theme_mod_id', array(
'type' => 'select', // select menu
'choices' => array(
// A: text output to get_theme_mod('theme_mod_id')
// B: theme mod option shown in customizer select menu
__('A1') => __( 'B1' ),
__('A2') => __( 'B2' ),
),
...
) );
This setup is fiddly to manage because setting a default value requires duplicating part of the array:
$wp_customize->add_setting( 'theme_mod_id', array(
'default' => 'A1',
...
) );
(this could also be done like this:)
get_theme_mod( 'theme_mod_id', 'A1' )
Using a separate array makes things DRYer:
$my_choices = array(
__('"Open Sans", sans-serif') => __( 'Sans-serif: Open Sans' ),
__('"Times New Roman", serif') => __( 'Serif: Times New Roman' ),
);
This is then added to the select choices:
$wp_customize->add_control('theme_mod_id', array(
'type' => 'select', // select menu
'choices' => $my_choices,
...
) );
And the default is set like so:
$wp_customize->add_setting( 'theme_mod_id', array(
'default' => array_shift( array_keys( $my_choices ) ), // returns first key
...
) );
http://php.net/manual/en/function.array-keys.php#59892
Here's how to get the first key, the last key, the first value or the last value of a (hash) array without explicitly copying nor altering the original array:
$array = array('first'=>'111', 'second'=>'222', 'third'=>'333');
// get the first key: returns 'first'
print array_shift(array_keys($array));
// get the last key: returns 'third'
print array_pop(array_keys($array));
// get the first value: returns '111'
print array_shift(array_values($array));
// get the last value: returns '333'
print array_pop(array_values($array));