Search

Laravel Array Helper Function: array_build

November 18, 2016 —John Koster

The $build helper method will create a new array with the original array's key/value pairs after they have been run through the $callback function. The $callback function should return an array with the new key and value.

The signature for the build helper method is:

build($array, callable $callback)

The following code sample will append is rare to the values in the original array:

1<?php
2 
3use Illuminate\Support\Arr;
4 
5$myArray = [
6 'animal' => 'Araripe Manakin',
7 'plant' => 'Pineland Wild Petunia'
8];
9 
10$myArray = Arr::build($myArray, function($key, $value)
11 {
12 return [$key, $value.' is rare'];
13 });

The final array would be:

1array(2) {
2 ["animal"] "Araripe Manakin is rare"
3 ["plant"] "Pineland Wild Petunia is rare"
4}

#array_build($array, callable $callback)

The array_build function is a shortcut to calling Arr::build. This function is declared in the global namespace.

Some absolutely amazing
people

The following amazing people help support this site and my open source projects ♥️
If you're interesting in supporting my work and want to show up on this list, check out my GitHub Sponsors Profile.