Skip to content

array_prepend

Tonya Mork edited this page Mar 12, 2017 · 1 revision

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.

Syntax

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

Example

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',
	),
);
*/

« Back to Array API

Clone this wiki locally