Skip to content

Instantly share code, notes, and snippets.

@veeeeeeeeeee
Last active January 17, 2019 04:35
Show Gist options
  • Save veeeeeeeeeee/698df3b25b120e6d64c13aca5c5876be to your computer and use it in GitHub Desktop.
Save veeeeeeeeeee/698df3b25b120e6d64c13aca5c5876be to your computer and use it in GitHub Desktop.
PHP snippets
// dump array key -> value without noise
function pprint($array) {
echo "<pre style=\"background-color: #ddd;\">";
print_r($array);
echo "</pre>";
}
function randomString($length) {
if (gettype($length) !== 'integer') {
$length = 30;
}
$string = base64_encode(openssl_random_pseudo_bytes($length));
return $string;
}
// [a] -> (a -> [b]) -> [b]
function _flatMap($arr, callable $fn) {
return array_merge([], ...array_map($fn, $arr));
}
function _flatMapK($arr, callable $fn) {
return array_merge([], ...array_map($fn, array_keys($arr), $arr));
}
// re-arranging parameters on FP-style built-in functions
// [a] -> (a -> b) -> [b]
function _map($arr, callable $callback) {
return array_map($callback, $arr);
}
// [v] -> (k -> v -> w) -> [w]
function _mapK($arr, callable $callback) {
return array_map($callback, array_keys($arr), $arr);
}
// [a] -> (a -> bool) -> [a]
function _filter($arr, callable $callback) {
return array_filter($arr, $callback);
}
// [v] -> (k -> v -> bool) -> [v]
function _filterK($arr, callable $callback) {
return array_filter($arr, $callback, ARRAY_FILTER_USE_BOTH);
}
// [a] -> b -> (b -> a -> b) -> [b]
function _reduce($arr, $init, callable $callback) {
return array_reduce($arr, $callback, $init);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment