Skip to content

array_set

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

The array_set() function sets the value for the given key within the array. If the element exists, then it's overwritten with the new value; else, the new element is added with the key.

For deeply nested arrays, use dot notation.

Syntax

array array_set( 
     array &$subjectArray, 
     string $key,
     mixed $newValue
);

Example 1

$user = array(
	'user_id'   => 504,
	'name'      => 'Bob Jones',
	'social'    => array(
		'twitter' => '@bobjones',
	),
);

$value = array_set( $user, 'social.twitter', '@realBobJones' );
// Returns: `@realBobJones`

The $user array is changed to:

$user = array( 'user_id' => 504, 'name' => 'Bob Jones', 'social' => array( 'twitter' => '@realBobJones', ), );

Example 2

$user = array(
	'user_id'   => 504,
	'name'      => 'Bob Jones',
	'social'    => array(
		'twitter' => '@bobjones',
	),
);

$value = array_set( $user, 'social.website', 'https://bobjones.com' );
/**
   Returns:

	array(
		'twitter' => '@realBobJones',
		'website' => 'https://bobjones.com',
	)
*/

The $user array is changed to:

$user = array(
	'user_id'   => 504,
	'name'      => 'Bob Jones',
	'social'    => array(
		'twitter' => '@realBobJones',
   		'website' => 'https://bobjones.com',
	),
);

« Back to Array API

Clone this wiki locally