phparraysarray-splice

Insert a new element at a specified position in an associative array and preserve keys


I currently have an array that holds an array of arrays:

    array(9) {
      ["enabled"]=>
      array(4) {
        ["title"]=>
        string(14) "Enable/Disable"
        ["type"]=>
        string(8) "checkbox"
        ["label"]=>
        string(25) "Enable"
        ["default"]=>
        string(3) "yes"
      }
    ["title"]=>
    array(5) {
    ["title"]=>
    string(5) "Title"
    ["type"]=>
    string(4) "text"
    ["description"]=>
    string(60) "This controls the title which the user sees during checkout."
    ["default"]=>
    string(18) "Retail Finance"
    ["desc_tip"]=>
    bool(true)
  }

This array is called $test. Now as you can see in this array there's an array called "enabled" at index 0, and an array called "title" at index 1. I'd like to splice another associative array between index 0 and 1. I've included this below:

'enable_finance_calculator' => array(
            'title' => __( 'Enable Calculator', 'woocommerce' ),
            'type' => 'checkbox',
            'label' => __( 'Enable Finance Calculator', 'woocommerce' ),
            'default' => 'yes'
        ),

Normally when doing this I'd use array_splice(), but this does not handle associative arrays. What is the best option here?


Solution

  • Kind of involved but you can slice and merge:

    $test = array_merge(
              array_slice($test, 0, $pos=array_search('enabled', array_keys($test), true)+1, true),
              $newarray,
              array_slice($test, $pos, NULL, true)
            );