Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 17 additions & 0 deletions src/Illuminate/Collections/Arr.php
Original file line number Diff line number Diff line change
Expand Up @@ -796,6 +796,23 @@ public static function set(&$array, $key, $value)
return $array;
}

/**
* Set an array item to a given value using "dot" notation only if the array key exists
*
* @param array $array
* @param string|int|null $key
* @param mixed $value
* @return array
*/
public static function setIfExists(&$array, $key, $value)
{
if (! static::exists($array, $key))) {
return $array;
}

return static::set($array, $key, $value);
}

/**
* Shuffle the given array and return the result.
*
Expand Down
13 changes: 13 additions & 0 deletions tests/Support/SupportArrTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -1040,6 +1040,19 @@ public function testSet()
$this->assertEquals([1 => 'hAz'], Arr::set($array, 1, 'hAz'));
}

public function testSetIfExists()
{
// key does not exist, nothing is set
$array = ['products' => ['desk' => ['price' => 100]]];
Arr::setIfExists($array, 'products.desk.currency', 'USD');
$this->assertEquals(['products' => ['desk' => ['price' => 100]]], $array);

// key exists
$array = ['products' => ['desk' => ['price' => 100]]];
Arr::setIfExists($array, 'products.desk.price', 200);
$this->assertEquals(['products' => ['desk' => ['price' => 200]]], $array);
}

public function testShuffleProducesDifferentShuffles()
{
$input = range('a', 'z');
Expand Down
Loading