Skip to content

Instantly share code, notes, and snippets.

@alastairparagas
Created August 2, 2018 04:26
Show Gist options
  • Select an option

  • Save alastairparagas/6e8cc1f15ea932da267791b605170ea3 to your computer and use it in GitHub Desktop.

Select an option

Save alastairparagas/6e8cc1f15ea932da267791b605170ea3 to your computer and use it in GitHub Desktop.
Functional Programming in PHP
<?php
$accumulator = function (
string $accumulated_string,
string $mapped_list_element
) {
return $accumulated_string . $mapped_list_element . "\n";
};
$mapped_array = array_reduce(
array_map(
function (int $list_element): string {
return "A list element: " . $list_element;
},
[1, 2, 3, 4]
),
$accumulator,
""
);
echo $mapped_array;
$filtered_array = array_reduce(
array_filter(
[1, 2, 3, 4],
function (int $list_element): bool {
return $list_element > 2;
}
),
$accumulator,
""
);
echo $filtered_array;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment