Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Insert a value or key/value pair after a specific key in an array. If key doesn't exist, value is appended to the end of the array.
<?php
/**
* Insert a value or key/value pair after a specific key in an array. If key doesn't exist, value is appended
* to the end of the array.
*
* @param array $array
* @param string $key
* @param array $new
*
* @return array
*/
function array_insert_after( array $array, $key, array $new ) {
$keys = array_keys( $array );
$index = array_search( $key, $keys );
$pos = false === $index ? count( $array ) : $index + 1;
return array_merge( array_slice( $array, 0, $pos ), $new, array_slice( $array, $pos ) );
}
@adam-godfrey
Copy link

adam-godfrey commented Aug 2, 2016

Example usage would be nice

@sirBlond
Copy link

sirBlond commented Feb 9, 2017

Example usage.

Code below will add phone type field into woocommerce checkout billing fields array after billing_phone field.

add_filter('woocommerce_billing_fields', 'wc_plugin_checkout_billing_fields', 10, 1);
function wc_plugin_checkout_billing_fields($address_fields) {
  $address_fields['billing_phone']['clear'] = false;
  $address_fields['billing_phone']['class'] = array('form-row-first');

  $billing_phone_type_field = array('billing_phone_type' => array(
    'type' => 'select',
    'label' => __('Phone Type', 'wc_plugin'),
    'required' => true,
    'class' => array('form-row-last'),
    'clear' => true,
    'options' => array(
      'work' => __('Work', 'wc_plugin'),
      'home' => __('Home', 'wc_plugin'),
      'mobile' => __('Mobile', 'wc_plugin')
    )
  ));
  $address_fields = array_insert_after($address_fields, 'billing_phone', $billing_phone_type_field);

  return $address_fields;
}

@nunzio-marfe
Copy link

nunzio-marfe commented Nov 28, 2018

Great Job!

@jpcaparas
Copy link

jpcaparas commented Feb 22, 2019

$index = array_search( $key, $keys );

Passing in true as a third argument ensures that a strict key search is performed, especially for associative arrays:

$index = array_search( $key, $keys, $strict = true );

@dillingham
Copy link

dillingham commented Jun 5, 2019

thanks for this

@ejaz-ul-haq
Copy link

ejaz-ul-haq commented Oct 26, 2020

function push_at_to_associative_array($array, $key, $new ){
        $keys  = array_keys( $array );
		$index = array_search( $key, $keys, true  );
        $pos   = false === $index ? count( $array ) : $index + 1;
        
        $array = array_slice($array, 0, $pos, true) + $new + array_slice($array, $pos, count($array) - 1, true);
        return $array;
    }

Use Case

$your_updated_orignal_parent_array = push_at_to_associative_array($your_orignal_parent_array, $orignal_parent_array_key, $new_child_single_or_multidimentional_array );

@edwinsnotje
Copy link

edwinsnotje commented Feb 17, 2021

Thanks

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment