Skip to content

Instantly share code, notes, and snippets.

@AucT
Created December 18, 2022 11:10
Show Gist options
  • Save AucT/a3662b21be6066e010346389e84e4cc3 to your computer and use it in GitHub Desktop.
Save AucT/a3662b21be6066e010346389e84e4cc3 to your computer and use it in GitHub Desktop.
pluck array
<?php
function pluckObject($arrayOfObjects, string $value, ?string $key = null): array
{
$data = [];
if ($key) {
foreach ($arrayOfObjects as $object) {
$data[$object->{$key}] = $object->{$value};
}
} else {
foreach ($arrayOfObjects as $object) {
$data[] = $object->{$value};
}
}
return $data;
}
function pluckArray(array $array, string $value, ?string $key = null): array
{
$data = [];
if ($key) {
foreach ($array as $object) {
$data[$object[$key]] = $object[$value];
}
} else {
foreach ($array as $object) {
$data[] = $object[$value];
}
}
return $data;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment