Skip to content

Commit

Permalink
Add array_set and Arr::set functionality
Browse files Browse the repository at this point in the history
  • Loading branch information
jdrieghe committed Jul 17, 2018
1 parent dd0bed6 commit 3178e1e
Show file tree
Hide file tree
Showing 3 changed files with 117 additions and 0 deletions.
30 changes: 30 additions & 0 deletions src/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,34 @@ public static function has(array $array, $key)

return true;
}

/**
* Set an array item to a given value using "dot" notation.
*
* @param array $array
* @param string $key
* @param mixed $value
* @return array
*/
public static function set(&$array, $key, $value)
{
$keys = explode('.', $key);

while (count($keys) > 1) {
$key = array_shift($keys);

// If the key doesn't exist at this depth, we will just create an empty array
// to hold the next value, allowing us to create the arrays to hold final
// values at the correct depth. Then we'll keep digging into the array.
if (! isset($array[$key]) || ! is_array($array[$key])) {
$array[$key] = [];
}

$array = &$array[$key];
}

$array[array_shift($keys)] = $value;

return $array;
}
}
5 changes: 5 additions & 0 deletions src/array-helpers.php
Original file line number Diff line number Diff line change
Expand Up @@ -11,3 +11,8 @@ function array_has($array, $key)
{
return Arr::has($array, $key);
}

function array_set(&$array, $key, $value)
{
return Arr::set($array, $key, $value);
}
82 changes: 82 additions & 0 deletions tests/ArraySetTest.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
<?php

namespace ArrayHelpers;

use PHPUnit\Framework\TestCase;

class ArraySetTest extends TestCase
{
public function testWillSetSingleValue()
{
$expected = ['rolling' => 'stones'];

$initial = [];
Arr::set($initial, 'rolling', 'stones');
$this->assertEquals($expected, $initial);

$initial = [];
array_set($initial, 'rolling', 'stones');
$this->assertEquals($expected, $initial);
}

public function testWillOverwriteExistingValue()
{
$initial = ['rolling' => 'stones'];
Arr::set($initial, 'rolling', 'thunder');
$this->assertEquals(
['rolling' => 'thunder'],
$initial
);
}

public function testWillSetUsingDotNotation()
{
$initial = [];
Arr::set($initial, "i.can't.get.no", 'satisfaction');
$this->assertEquals(
[
'i' => [
"can't" => [
'get' => [
'no' => 'satisfaction',
],
],
],
],
$initial
);
}

public function testWillOnlyPartiallyOverwriteUsingDotNotation()
{
$initial = [
'i' => [
"can't" => [
'live' => [
'in' => [
'a' => 'living room',
]
]
]
]
];
Arr::set($initial, "i.can't.get.no", 'satisfaction');
$this->assertEquals(
[
'i' => [
"can't" => [
'live' => [
'in' => [
'a' => 'living room',
],
],
'get' => [
'no' => 'satisfaction',
],
],
],
],
$initial
);
}
}

0 comments on commit 3178e1e

Please sign in to comment.