0

How to suppress a key from a multidimensional array and get the next occurrence key.

$array_example = array(

    'default_group' => 'styling',

    'general'   => esc_html__('General', THEMETEXTDOMAIN),

    // User can enter it here
    // 'default_group' => 'styling',

    'styling'   => esc_html__('Styling', THEMETEXTDOMAIN),

    // 'default_group' => 'styling',

    'animate'   => esc_html__('Animate', THEMETEXTDOMAIN),
)

[default_group] key is a fixed key but it might be at any position.

I need to get the next key if the [default_group] key not exist or it has an empty value.

if( array_key_exists( 'default_group', $array_example ) && !empty( $array_example['default_group'] ) ) {

     $col_group_default = sanitize_text_field( $array_example['default_group'] );

} else {

     // Here I want to get the key BUT NOT [default_group]                                

}
Hady Shaltout
  • 606
  • 1
  • 9
  • 22

1 Answers1

0
$choice = '';
$default = array_search('default_group', array_keys($array_example));

if ( $default && !empty($array_example[ $default ]) ) {
  $choice = $array_example[ $default ];
} else {
  $choice = isset($array_example[ $default + 1]) ? $array_example[ $default + 1] : $array_example[0];
}
RST
  • 3,899
  • 2
  • 20
  • 33
  • 3
    Welcome to stackov.... oh wait, you're here long enough to know that "here are teh codez" answers are not really helpful. Please try to explain how and why the code you posted solves OPs problem. – LJᛃ Feb 28 '17 at 04:03
  • Extended code to also include the scenario of `$default` being empty last element, which makes `$default+1` invalid. – RST Feb 28 '17 at 13:19
  • @LJᛃ I think you are wrong. I am using the exact logic the Op is already using, just different functions. Functions with a pretty much selfexplaining name. What you describe would be right if I just threw some code at a topic lik this one, http://stackoverflow.com/questions/42529018/combing-value-of-same-elements, which I do not. – RST Mar 01 '17 at 10:25