-
Notifications
You must be signed in to change notification settings - Fork 1
array_prepend
The array_prepend()
function prepends a new element onto the beginning of the subject array.
For indexed arrays, the numerical keys will be re-indexed starting at zero. Literal keys are not changed.
Caution: When passing a literal key, make sure it does not already to exist in the subject array, as arrays cannot have duplicate keys.
Note: This function does not use dot notation.
array array_prepend(
array $subjectArray,
mixed $newElementValue,
[ string|int $key = '' ]
);
Where:
$subjectArray
is the array to work on and contains the subset you want
$newElementValue
is the value to prepend onto the subject array
$key
(optional) is the key you want to assign to the new element
For this dataset, let's prepend a new element onto the beginning of it.
$dataSet = array(
'names' => array(
'developer1' => 'Tonya',
'developer2' => 'Sally',
'developer3' => 'Mike',
),
'emails' => array(
'developer1' => 'foo',
'developer2' => 'bar',
'developer3' => 'baz',
),
);
Let's add some twitter handles:
$twitterHandles = array(
'developer1' => '@foo',
'developer2' => '@bar',
'developer3' => '@baz',
);
$result = array_prepend( $dataSet, $twitterHandles );
/**
Returns:
array(
array(
'developer1' => '@foo',
'developer2' => '@bar',
'developer3' => '@baz',
),
'names' => array(
'developer1' => 'Tonya',
'developer2' => 'Sally',
'developer3' => 'Mike',
),
'emails' => array(
'developer1' => 'foo',
'developer2' => 'bar',
'developer3' => 'baz',
),
);
*/
Now, if you want to specify a key for new element, do the following:
$result = array_prepend( $dataSet, $twitterHandles, 'twitter' );
/**
Returns:
array(
'twitter' => array(
'developer1' => '@foo',
'developer2' => '@bar',
'developer3' => '@baz',
),
'names' => array(
'developer1' => 'Tonya',
'developer2' => 'Sally',
'developer3' => 'Mike',
),
'emails' => array(
'developer1' => 'foo',
'developer2' => 'bar',
'developer3' => 'baz',
),
);
*/