Skip to content

Instantly share code, notes, and snippets.

@dotherightthing
Created August 15, 2019 09:29
Show Gist options
  • Save dotherightthing/92e31b5e48a2751d6495a17e8cdc5b87 to your computer and use it in GitHub Desktop.
Save dotherightthing/92e31b5e48a2751d6495a17e8cdc5b87 to your computer and use it in GitHub Desktop.
[Output keys from a hash array] #wordpress

Output keys from a hash array

Created: 2017.04.12

Get the first key, the last key, the first value or the last value of a (hash) array

WET WordPress approach

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' )

DRY WordPress approach

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
  ...
) );

array_keys

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));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment