Skip to content

Instantly share code, notes, and snippets.

@amnuts

amnuts/stuff.php

Last active Mar 10, 2021
Embed
What would you like to do?
jotting down functions
<?php
// Return greatest common divider of two numbers
function gcd($a, $b) {
return $b ? gcd($b, $a % $b) : $a;
}
// Returns the least common multiple of two or more numbers.
function lcm(...$numbers): int
{
$ans = $numbers[0];
for ($i = 1, $max = count($numbers); $i < $max; $i++) {
$ans = (($numbers[$i] * $ans) / gcd($numbers[$i], $ans));
}
return $ans;
}
lcm(12, 7); // 84
lcm(1, 3, 4, 5); // 60
/**
* @param string $needle Such as, `/^AWS_/`
* @param array $input An associative array
* @return array
*/
function preg_grep_keys(string $needle, array $haystack): array {
return array_intersect_key($haystack, array_flip(preg_grep($needle, array_keys($haystack))));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment