Arrays in PHP are used very widely. There are many functions for working with arrays. Let's check some of them and how they are used in Laravel open-source projects.
is_array()
and count()
One of the functions used often is checking if a variable is an array. In this example from Filament, first, it is checked if $state
is an array, and if it is, then counts all elements in an array.
public function getItemsCount(): int{ $state = $this->getState(); return is_array($state) ? count($state) : 0;}
Link to the example in GitHub repository.
array_merge()
and array_filter()
A common situation is to merge arrays into one. Another situation is to filter out array keys with null values. In this example from Laravel Jetstream, two arrays are merged and filter keys with values that aren't true.
class ShareInertiaData{ public function handle($request, $next) { Inertia::share(array_filter([ // ... 'auth' => [ 'user' => function () use ($request) { if (! $user = $request->user()) { return; } $userHasTeamFeatures = Jetstream::userHasTeamFeatures($user); if ($user && $userHasTeamFeatures) { $user->currentTeam; } return array_merge($user->toArray(), array_filter([ 'all_teams' => $userHasTeamFeatures ? $user->allTeams()->values() : null, ]), [ 'two_factor_enabled' => Features::enabled(Features::twoFactorAuthentication()) && ! is_null($user->two_factor_secret), ]); }, ], // ... ])); return $next($request); }}
Link to the example in GitHub repository.
array_push()
We can quickly push one or more elements to the end of an array. Here is an example from crater open-source project.
class FilePermissionChecker{ protected $results = []; public function __construct() { $this->results['permissions'] = []; $this->results['errors'] = null; } // ... private function addFile($folder, $permission, $isSet) { array_push($this->results['permissions'], [ 'folder' => $folder, 'permission' => $permission, 'isSet' => $isSet, ]); } // ...}
Link to the example in GitHub repository.
array_map()
We can use the array_map()
function to do some actions to array elements.
In this example from pixelfed, the array_map()
is used to make elements into lowercase using the strtolower()
PHP function.
class FixUsernames extends Command{ // ... protected function restrictedCheck() { $affected = collect([]); $restricted = RestrictedNames::get(); $users = User::chunk(100, function($users) use($affected, $restricted) { foreach($users as $user) { if($user->is_admin || $user->status == 'deleted') { continue; } if(in_array(strtolower($user->username), array_map('strtolower', $restricted))) { $affected->push($user); } $val = str_replace(['-', '_', '.'], '', $user->username); if(!ctype_alnum($val)) { $this->info('Found invalid username: ' . $user->username); $affected->push($user); } } }); // ... } // ...}
Link to the example in GitHub repository.
implode()
and array_map()
You can also use callback with the array_map()
. In this erpsaas open-source project, the callback is used to add a bullet symbol and implode to add a string for every element.
class CategoryResource extends Resource{ // ... public static function table(Table $table): Table { return $table // ... ->bulkActions([ Tables\Actions\BulkActionGroup::make([ Tables\Actions\DeleteBulkAction::make() ->before(static function (Collection $records, Tables\Actions\DeleteBulkAction $action) { $defaultCategories = $records->filter(static function (Category $record) { return $record->enabled; }); if ($defaultCategories->isNotEmpty()) { $defaultCategoryNames = $defaultCategories->pluck('name')->toArray(); Notification::make() ->danger() ->title('Action Denied') ->body(static function () use ($defaultCategoryNames) { $message = __('The following categories are currently set as your default and cannot be deleted. Please set a different category as your default before attempting to delete these ones.') . '<br><br>'; $message .= implode('<br>', array_map(static function ($name) { return '• ' . $name; }, $defaultCategoryNames)); return $message; }) ->persistent() ->send(); $action->cancel(); } }), ]), ]) ->emptyStateActions([ Tables\Actions\CreateAction::make(), ]); } // ...}
Link to the example in GitHub repository.
array_keys()
and array_values()
This example comes from the Laravel framework. Laravel has helpers, some of which are for working with arrays.
The Arr:divide()
uses the array_keys
and array_values
to return two arrays from one: one containing the keys and the other containing the values of the given array.
class Arr{ // ... public static function divide($array) { return [array_keys($array), array_values($array)]; } // ...}
Link to the example in GitHub repository.
array_unique()
The array_unique()
function removes duplicate values from an array.
An example is from the open-source project LinkAce, where array_unique
gets unique error messages.
@include('flash::message') @if ($errors->any()) <div class="alert alert-danger"> <ul class="mb-0 list-unstyled"> @foreach (array_unique($errors->all()) as $error) <li>{{ $error }}</li> @endforeach </ul> </div>@endif
Link to the example in GitHub repository.
array_search()
When doing array_search()
, it will return the first key where the given value exists.
An example is from an open-source project free pmo.
class Role extends ReferenceAbstract{ protected static $lists = [ 1 => 'admin', 2 => 'worker', ]; // ... public static function getIdByName($roleName) { return array_search($roleName, static::$lists); } // ...}
Link to the example in GitHub repository.