mcaskill / php-array-insert
Insert elements from a passed array into the first array.
1.0.0
2017-11-24 13:56 UTC
Requires
- php: >=5.4.0
This package is not auto-updated.
Last update: 2025-10-18 01:37:14 UTC
README
(PHP 5 >= 5.4)
array_insert — Insert an array into another array before/after a given key.
Description
array array_insert( array $input, mixed $insert, mixed $key [, string $pos = 'after' ] )
Merge the elements of the $array array after, or before, the designated $key from the $input array. It returns the resulting array.
Parameters
$array— The input array.$insert— The value to merge.$key— The key from the$inputto merge$insertnext to.$pos— Wether to splice$insertbefore or after the$key. Can be either "before" or "after" (the default).
Return Values
Returns the resulting array.
Errors/Exceptions
If $key is not one of the accepted types E_USER_ERROR will be thrown and NULL returned.
Examples
Example #1 array_insert() example
$arr1 = [
"name" => [
"type" => "string",
"maxlength" => "30",
],
"email" => [
"type" => "email",
"maxlength" => "150",
],
];
$ins1 = [
"phone" => [
"type" => "string",
"format" => "phone",
],
];
array_insert( $arr1, $ins1, "email" );
$arr2 = ["one", "two", "three"];
array_insert( $arr2, "one-half", 1, "before" );
The above example will output:
Array(
'name' => Array(
'type' => 'string',
'maxlength' => '30',
),
'email' => Array(
'type' => 'email',
'maxlength' => '150',
),
'phone' => Array(
'type' => 'string',
'format' => 'phone',
),
)
Array(
0 => 'one',
1 => 'one-half',
2 => 'two',
3 => 'three',
)
Installation
With Composer
$ composer require mcaskill/php-array-insert
Without Composer
Why are you not using composer? Download Function.Array-Insert.php from the gist and save the file into your project path somewhere.