Skip to content

Instantly share code, notes, and snippets.

@halilim
Last active December 22, 2015 23:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save halilim/6548065 to your computer and use it in GitHub Desktop.
Save halilim/6548065 to your computer and use it in GitHub Desktop.
A PHP function that can insert at both integer and string positions

Example usage:

$arr = [
    "name"  => [
        "type"      => "string",
        "maxlength" => "30",
    ],
    "email" => [
        "type"      => "email",
        "maxlength" => "150",
    ],
];

$arr2 = ["one", "two", "three"];

array_insert(
    $arr,
    "email",
    [
        "phone" => [
            "type"   => "string",
            "format" => "phone",
        ],
    ]
);

array_insert(
    $arr2,
    1,
    "on-half"
);

Result:

array (
  'name' =>
  array (
    'type' => 'string',
    'maxlength' => '30',
  ),
  'phone' =>
  array (
    'type' => 'string',
    'format' => 'phone',
  ),
  'email' =>
  array (
    'type' => 'email',
    'maxlength' => '150',
  ),
)
array (
  0 => 'one',
  1 => 'on-half',
  2 => 'two',
  3 => 'three',
)
<?php
/**
* A function that can insert at both integer and string positions
*
* @param array $array
* @param int|string $position
* @param mixed $insert
*/
function array_insert(&$array, $position, $insert)
{
if (is_int($position)) {
array_splice($array, $position, 0, $insert);
} else {
$pos = array_search($position, array_keys($array));
$array = array_merge(
array_slice($array, 0, $pos),
$insert,
array_slice($array, $pos)
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment