Skip to content

[12.x] Add Arr::push() #56632

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

Merged
merged 3 commits into from
Aug 13, 2025
Merged

[12.x] Add Arr::push() #56632

merged 3 commits into from
Aug 13, 2025

Conversation

inxilpro
Copy link
Contributor

@inxilpro inxilpro commented Aug 12, 2025

Often times I find myself wanting to push something to an array (if the array exists), or initialize it to an empty array and then push it (if the array doesn't exist yet). For example:

if ($this->hasChanges($data)) {
  Arr::push($result, 'pending.changes', $data);
}

In this case, if $result['pending']['changes'] does not yet exist, it's created as an empty array, then $data is pushed to it (and if it's already an array, $data is pushed to the existing one).

Why not a macro? This isn't something you can implement simply using Arr::macro because macros don't pass values by reference.

(This is a function that I reach for every month or so, and each time manage to surprise myself when I can't find it on the Arr helper 😂)

inxilpro and others added 3 commits August 12, 2025 15:05
Introduces Arr::push to append items to arrays using dot notation. Includes tests for pushing values to nested arrays, handling null keys, and exception cases for invalid types.
This better matches array_push's signature
@taylorotwell taylorotwell merged commit 41e7719 into laravel:12.x Aug 13, 2025
60 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants