Skip to content

Instantly share code, notes, and snippets.

@piorus
Last active October 31, 2022 07:35
Show Gist options
  • Save piorus/ae25c0be53a9d3a35de89e4bfc571ba7 to your computer and use it in GitHub Desktop.
Save piorus/ae25c0be53a9d3a35de89e4bfc571ba7 to your computer and use it in GitHub Desktop.
PHP Snippets

Remove key prefix from associative array

<?php

function remove_key_prefix( $prefix, $array ) {
    return array_combine(
        // remove key prefix
        array_map(function($v) use ($prefix) {
            return str_replace( $prefix, '', $v );
        }, array_keys( $array ) ),
        // ...and merge with values
        array_values( $array )
    );
}

/**
* EXAMPLE USAGE BELOW
*/

$in = array(
    'item_title'    => 'I like trains',
    'item_content   => 'I'm really big train enthusiast.'
);

$out = remove_key_prefix('item_', $in);

/**
* Returns:
*   array(
*      'title'     => 'I like trains',
*      'content'   => 'I'm really big train enthusiast.'
*  )
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment