Skip to content

Commit 9b6d42d

Browse files
committed
feat: Add ArrayUtils::setElement recursive static method to manipulate deep arrays and create missing key levels from a path list.
1 parent f62a395 commit 9b6d42d

File tree

2 files changed

+59
-0
lines changed

2 files changed

+59
-0
lines changed

lib/Horde/Array.php

Lines changed: 30 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -105,6 +105,36 @@ public static function getElement(&$array, array &$keys, $value = null)
105105
return $array;
106106
}
107107

108+
/**
109+
* Using an array of keys iterate through the $array following the
110+
* nested $keys to find the final key's value. If a $value is passed then set
111+
* that value. If missing, create array levels along that path.
112+
* Existing values in that path will be overwritten even if $value is null.
113+
*
114+
* @param array &$array The array to be used.
115+
* @param array &$keys The key path to follow as an array.
116+
* @param array $value Target element will have this value set
117+
* to it.
118+
*
119+
* @return mixed The final value of the key path.
120+
*/
121+
public static function setElement(&$array, array &$keys, $value = null)
122+
{
123+
if (count($keys)) {
124+
$key = array_shift($keys);
125+
if (!isset($array[$key])) {
126+
$array[$key] = array();
127+
}
128+
return isset($array[$key])
129+
? self::setElement($array[$key], $keys, $value)
130+
: false;
131+
}
132+
133+
$array = $value;
134+
135+
return $array;
136+
}
137+
108138
/**
109139
* Returns a rectangle of a two-dimensional array.
110140
*

src/ArrayUtils.php

Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -113,6 +113,35 @@ public static function getElement(&$array, array &$keys, $value = null)
113113

114114
return $array;
115115
}
116+
/**
117+
* Using an array of keys iterate through the $array following the
118+
* nested $keys to find the final key's value. If a $value is passed then set
119+
* that value. If missing, create array levels along that path.
120+
* Existing values in that path will be overwritten even if $value is null.
121+
*
122+
* @param array &$array The array to be used.
123+
* @param array &$keys The key path to follow as an array.
124+
* @param array $value Target element will have this value set
125+
* to it.
126+
*
127+
* @return mixed The final value of the key path.
128+
*/
129+
public static function setElement(&$array, array &$keys, $value = null)
130+
{
131+
if (count($keys)) {
132+
$key = array_shift($keys);
133+
if (!isset($array[$key])) {
134+
$array[$key] = array();
135+
}
136+
return isset($array[$key])
137+
? self::setElement($array[$key], $keys, $value)
138+
: false;
139+
}
140+
141+
$array = $value;
142+
143+
return $array;
144+
}
116145

117146
/**
118147
* Returns a rectangle of a two-dimensional array.

0 commit comments

Comments
 (0)