Oihana PHP

set.php

Table of Contents

Functions

set()  : array<string|int, mixed>
Sets a value in an associative array using a key path.

Functions

set()

Sets a value in an associative array using a key path.

set(array<string|int, mixed> &$array, string|null $key, mixed $value[, string $separator = '.' ][, bool $copy = false ]) : array<string|int, mixed>

If no key is given to the method, the entire array will be replaced.

Parameters
$array : array<string|int, mixed>

The associative array to modify (by reference).

$key : string|null

The key path as a string. Can be null, in which case the function replaces the entire array.

$value : mixed

The value to set.

$separator : string = '.'

The separator used to split the key into segments. Defaults to a dot ('.').

$copy : bool = false

If true, returns a modified copy instead of altering the original array.

Tags
example
$data = [];
set( $data , 'user.name' , 'Alice' ) ;
// $data => ['user' => ['name' => 'Alice']]

set( $data , null, ['id' => 1] ) ;
// $data => ['id' => 1]

$data = ['user' => ['name' => 'Marc']];
$new = set($data, 'user.address.country', 'France', '.', true);
print_r( $new ); // ['user' => ['name' => 'Marc', 'address' => ['country' => 'France']]]
author

Marc Alcaraz (ekameleon)

since
1.0.0
Return values
array<string|int, mixed>

The updated ( or copied and modified ) array.


        
On this page

Search results