-
Notifications
You must be signed in to change notification settings - Fork 11.3k
Add setIfExists() to Arr #55489
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Add setIfExists() to Arr #55489
Conversation
If the maintainers believe this should be added, having a symmetric The argument is similar to this PR, when one wants to be sure that all records, in a record set, have the same fields available, and potentially fill missing fields with default values, for example, for an export. Either way, in my opinion, I would add both cases as macros to a project which needs either of those. |
Arr::set behave the same way as setIfDoesntExists hence why I add this setIfExists maybe Arr::setOnlyIfExists is a better method name than Arr::setIfExists |
No. Maybe I wasn't clear when explaining.
For example, if one wants to make sure all records have the same fields available: $recordset = [
['name' => 'John'],
['name' => 'Mary', 'age' => 21],
];
foreach($records as $record) {
Arr::setIfDoesntExists($record, 'name', 'NA');
Arr::setIfDoesntExists($record, 'age', 'NA');
}
print_r($recordset);
/*
$recordset = [
['name' => 'John', 'age' => 'NA'],
['name' => 'Mary', 'age' => 21],
];
*/
|
Well, as I said before, I think both options are niche, and could be added as macros to a project if needed. The example, from my previous comment, could be replaced with the null-coalescing assignment: foreach($records as $record) {
$record['name'] ??= 'NA';
$record['age'] ??= 'NA';
} Unless one want to preserve pre-existing |
Do we have Fluent for arrays? I always forget and there isn't much on Fluent besides for strings on the docs. It would be cool if we could do something like Arr::whenExists($arr, 'key')->set('key', 'value'); or Arr::fluent($arr)->whenExists('key')->set('key', 'value'); |
We have Regarding the PR, I don't think it's feasible anyway to add more stuff in |
Thanks for your pull request to Laravel! Unfortunately, I'm going to delay merging this code for now. To preserve our ability to adequately maintain the framework, we need to be very careful regarding the amount of code we include. If applicable, please consider releasing your code as a package so that the community can still take advantage of your contributions! |
Usage
Example 1:
This returns you ['name' => 'Jane'] as it will not be set as the 'price' key does not exist in the array
Example 2:
This returns you ['name' => 'Jack'] as the key exist in the original array
I think this method can be quite convenient if you want to iterate over an array to replace certain PIIs with faker data only if the array contain certain json keys but otherwise you do not want to add new keys to the original payload array