nguyenanhung / 30-seconds-of-php-code
一个精选的PHP代码片段集合,您可以在30秒或更短的时间内理解。
Requires
- jbzoo/data: 1.6.0
- jbzoo/utils: 1.7.11
- mobiledetect/mobiledetectlib: ^2.8
- nesbot/carbon: 1.36.1
- symfony/filesystem: 3.4.17
- symfony/polyfill: ^1.9
- theseer/directoryscanner: 1.3.2
- zendframework/zend-escaper: ^2.6
Requires (Dev)
- alchemy/zippy: 0.4.9
- kint-php/kint: ^3.0
- symfony/console: ^3.4
README
30秒PHP代码
一个精选的PHP代码片段集合,您可以在30秒或更短的时间内理解。
注意:本项目灵感来源于30 Seconds of Code,但与该项目无关。
目录
📚 数组
查看内容
➗ 数学
查看内容
📜 字符串
查看内容
🎛️ 函数
📚 数组
all
如果提供的函数对所有数组元素都返回 true
,则返回 true
,否则返回 false
。
function all($items, $func) { return count(array_filter($items, $func)) === count($items); }
示例
all([2, 3, 4, 5], function ($item) { return $item > 1; }); // true
any
如果提供的函数至少对一个数组元素返回 true
,则返回 true
,否则返回 false
。
function any($items, $func) { return count(array_filter($items, $func)) > 0; }
示例
any([1, 2, 3, 4], function ($item) { return $item < 2; }); // true
chunk
将数组分成指定大小的更小数组。
function chunk($items, $size) { return array_chunk($items, $size); }
示例
chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]
deepFlatten
深度展开数组。
function deepFlatten($items) { $result = []; foreach ($items as $item) { if (!is_array($item)) { $result[] = $item; } else { $result = array_merge($result, deepFlatten($item)); } } return $result; }
示例
deepFlatten([1, [2], [[3], 4], 5]); // [1, 2, 3, 4, 5]
drop
返回一个新数组,从左侧移除了 n
个元素。
function drop($items, $n = 1) { return array_slice($items, $n); }
示例
drop([1, 2, 3]); // [2,3] drop([1, 2, 3], 2); // [3]
findLast
返回最后一个返回真实值的元素。
function findLast($items, $func) { $filteredItems = array_filter($items, $func); return array_pop($filteredItems); }
示例
findLast([1, 2, 3, 4], function ($n) { return ($n % 2) === 1; }); // 3
findLastIndex
返回最后一个返回真实值的元素的索引。
function findLastIndex($items, $func) { $keys = array_keys(array_filter($items, $func)); return array_pop($keys); }
示例
findLastIndex([1, 2, 3, 4], function ($n) { return ($n % 2) === 1; }); // 2
flatten
展开数组到一层的深度。
function flatten($items) { $result = []; foreach ($items as $item) { if (!is_array($item)) { $result[] = $item; } else { $result = array_merge($result, array_values($item)); } } return $result; }
示例
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
groupBy
根据给定的函数对数组的元素进行分组。
function groupBy($items, $func) { $group = []; foreach ($items as $item) { if ((!is_string($func) && is_callable($func)) || function_exists($func)) { $key = call_user_func($func, $item); $group[$key][] = $item; } elseif (is_object($item)) { $group[$item->{$func}][] = $item; } elseif (isset($item[$func])) { $group[$item[$func]][] = $item; } } return $group; }
示例
groupBy(['one', 'two', 'three'], 'strlen'); // [3 => ['one', 'two'], 5 => ['three']]
hasDuplicates
检查平坦列表是否存在重复值。如果存在重复值,则返回 true
,否则返回 false
。
function hasDuplicates($items) { return count($items) > count(array_unique($items)); }
示例
hasDuplicates([1, 2, 3, 4, 5, 5]); // true
head
返回列表的头部。
function head($items) { return reset($items); }
示例
head([1, 2, 3]); // 1
last
返回数组中的最后一个元素。
function last($items) { return end($items); }
示例
last([1, 2, 3]); // 3
pluck
检索给定键的所有值。
function pluck($items, $key) { return array_map( function($item) use ($key) { return is_object($item) ? $item->$key : $item[$key]; }, $items); }
示例
pluck([ ['product_id' => 'prod-100', 'name' => 'Desk'], ['product_id' => 'prod-200', 'name' => 'Chair'], ], 'name'); // ['Desk', 'Chair']
pull
修改原始数组以过滤掉指定的值。
function pull(&$items, ...$params) { $items = array_values(array_diff($items, $params)); return $items; }
示例
$items = ['a', 'b', 'c', 'a', 'b', 'c']; pull($items, 'a', 'c'); // $items will be ['b', 'b']
reject
使用给定的回调函数过滤收集。
function reject($items, $func) { return array_values(array_diff($items, array_filter($items, $func))); }
示例
reject(['Apple', 'Pear', 'Kiwi', 'Banana'], function ($item) { return strlen($item) > 4; }); // ['Pear', 'Kiwi']
remove
移除数组中返回 false
的元素。
function remove($items, $func) { $filtered = array_filter($items, $func); return array_diff_key($items, $filtered); }
示例
remove([1, 2, 3, 4], function ($n) { return ($n % 2) === 0; }); // [0 => 1, 2 => 3]
tail
返回除了第一个元素之外的所有元素。
function tail($items) { return count($items) > 1 ? array_slice($items, 1) : $items; }
示例
tail([1, 2, 3]); // [2, 3]
take
返回从开始移除 n
个元素的新数组。
function take($items, $n = 1) { return array_slice($items, 0, $n); }
示例
take([1, 2, 3], 5); // [1, 2, 3] take([1, 2, 3, 4, 5], 2); // [1, 2]
without
过滤掉数组中具有指定值之一的元素。
function without($items, ...$params) { return array_values(array_diff($items, $params)); }
示例
without([2, 1, 2, 3], 1, 2); // [3]
orderBy
根据键对数组或对象的集合进行排序。
function orderBy($items, $attr, $order) { $sortedItems = []; foreach ($items as $item) { $key = is_object($item) ? $item->{$attr} : $item[$attr]; $sortedItems[$key] = $item; } if ($order === 'desc') { krsort($sortedItems); } else { ksort($sortedItems); } return array_values($sortedItems); }
示例
orderBy( [ ['id' => 2, 'name' => 'Joy'], ['id' => 3, 'name' => 'Khaja'], ['id' => 1, 'name' => 'Raja'] ], 'id', 'desc' ); // [['id' => 3, 'name' => 'Khaja'], ['id' => 2, 'name' => 'Joy'], ['id' => 1, 'name' => 'Raja']]
➗ 数学
average
返回两个或更多数字的平均值。
function average(...$items) { return count($items) === 0 ? 0 : array_sum($items) / count($items); }
示例
average(1, 2, 3); // 2
factorial
计算一个数的阶乘。
function factorial($n) { if ($n <= 1) { return 1; } return $n * factorial($n - 1); }
示例
factorial(6); // 720
fibonacci
生成一个包含斐波那契序列的数组,直到第 n
项。
function fibonacci($n) { $sequence = [0, 1]; for ($i = 2; $i < $n; $i++) { $sequence[$i] = $sequence[$i-1] + $sequence[$i-2]; } return $sequence; }
示例
fibonacci(6); // [0, 1, 1, 2, 3, 5]
gcd
计算两个或更多数字的最大公约数。
function gcd(...$numbers) { if (count($numbers) > 2) { return array_reduce($numbers, 'gcd'); } $r = $numbers[0] % $numbers[1]; return $r === 0 ? abs($numbers[1]) : gcd($numbers[1], $r); }
示例
gcd(8, 36); // 4 gcd(12, 8, 32); // 4
isEven
如果给定数字是偶数,则返回 true
,否则返回 false
。
function isEven($number) { return ($number % 2) === 0; }
示例
isEven(4); // true
isPrime
检查提供的整数是否是素数。
function isPrime($number) { $boundary = floor(sqrt($number)); for ($i = 2; $i <= $boundary; $i++) { if ($number % $i === 0) { return false; } } return $number >= 2; }
示例
isPrime(3); // true
lcm
返回两个或更多数字的最小公倍数。
function lcm(...$numbers) { $ans = $numbers[0]; for ($i = 1; $i < count($numbers); $i++) { $ans = ((($numbers[$i] * $ans)) / (gcd($numbers[$i], $ans))); } return $ans; }
示例
lcm(12, 7); // 84 lcm(1, 3, 4, 5); // 60
median
返回数字数组的中间值。
function median($numbers) { sort($numbers); $totalNumbers = count($numbers); $mid = floor($totalNumbers / 2); return ($totalNumbers % 2) === 0 ? ($numbers[$mid - 1] + $numbers[$mid]) / 2 : $numbers[$mid]; }
示例
median([1, 3, 3, 6, 7, 8, 9]); // 6 median([1, 2, 3, 6, 7, 9]); // 4.5
maxN
返回数组中的 n 个最大元素。
function maxN($numbers) { $maxValue = max($numbers); $maxValueArray = array_filter($numbers, function ($value) use ($maxValue) { return $maxValue === $value; }); return count($maxValueArray); }
示例
maxN([1, 2, 3, 4, 5, 5]); // 2 maxN([1, 2, 3, 4, 5]); // 1
minN
返回数组中的 n 个最小元素。
function minN($numbers) { $minValue = min($numbers); $minValueArray = array_filter($numbers, function ($value) use ($minValue) { return $minValue === $value; }); return count($minValueArray); }
示例
minN([1, 1, 2, 3, 4, 5, 5]); // 2 minN([1, 2, 3, 4, 5]); // 1
approximatelyEqual
检查两个数字是否近似相等。
使用abs()比较两个值的绝对差值与epsilon。省略第三个参数epsilon,将使用默认值0.001。
function approximatelyEqual($number1, $number2, $epsilon = 0.001) { return abs($number1 - $number2) < $epsilon; }
示例
approximatelyEqual(10.0, 10.00001); // true approximatelyEqual(10.0, 10.01); // false
clampNumber
将num限制在由边界值a和b指定的包含范围内。
如果num在范围内,则返回num。否则,返回范围中的最近数。
function clampNumber($num, $a, $b) { return max(min($num, max($a, $b)), min($a, $b)); }
示例
clampNumber(2, 3, 5); // 3 clampNumber(1, -1, -5); // -1
📜 字符串
endsWith
检查字符串是否以指定的子字符串结束。
function endsWith($haystack, $needle) { return strrpos($haystack, $needle) === (strlen($haystack) - strlen($needle)); }
示例
endsWith('Hi, this is me', 'me'); // true
firstStringBetween
返回参数start和end之间的第一个字符串。
function firstStringBetween($haystack, $start, $end) { return trim(strstr(strstr($haystack, $start), $end, true), $start . $end); }
示例
firstStringBetween('This is a [custom] string', '[', ']'); // custom
isAnagram
比较两个字符串,如果都是字母表中的字母且字符相同,则返回true
,否则返回false
。
function isAnagram($string1, $string2) { return count_chars($string1, 1) === count_chars($string2, 1); }
示例
isAnagram('act', 'cat'); // true
isLowerCase
如果给定的字符串是小写,则返回true
,否则返回false
。
function isLowerCase($string) { return $string === strtolower($string); }
示例
isLowerCase('Morning shows the day!'); // false isLowerCase('hello'); // true
isUpperCase
如果给定的字符串是大写,则返回true
,否则返回false
。
function isUpperCase($string) { return $string === strtoupper($string); }
示例
isUpperCase('MORNING SHOWS THE DAY!'); // true isUpperCase('qUick Fox'); // false
palindrome
如果给定的字符串是回文,则返回true
,否则返回false
。
function palindrome($string) { return strrev($string) === (string) $string; }
示例
palindrome('racecar'); // true palindrome(2221222); // true
startsWith
检查字符串是否以给定的子字符串开头。
function startsWith($haystack, $needle) { return strpos($haystack, $needle) === 0; }
示例
startsWith('Hi, this is me', 'Hi'); // true
countVowels
返回提供的字符串中的元音字母数量。
使用正则表达式计算字符串中元音(A,E,I,O,U)的数量。
function countVowels($string) { preg_match_all('/[aeiou]/i', $string, $matches); return count($matches[0]); }
示例
countVowels('sampleInput'); // 4
decapitalize
将字符串的第一个字母转换为小写。
将字符串的第一个字母转换为小写后,与字符串的其余部分相连接。省略upperRest
参数以保持字符串的其余部分不变,或将它设置为true
以转换为大写。
function decapitalize($string, $upperRest = false) { return lcfirst($upperRest ? strtoupper($string) : $string); }
示例
decapitalize('FooBar'); // 'fooBar'
isContains
检查单词/子字符串是否存在于给定的字符串输入中。使用strpos
在字符串中查找子字符串第一次出现的位置。返回true
或false
。
function isContains($string, $needle) { return strpos($string, $needle); }
示例
isContains('This is an example string', 'example'); // true
isContains('This is an example string', 'hello'); // false
🎛️ 函数
compose
返回一个新函数,该函数将多个函数组合成一个可调用的函数。
function compose(...$functions) { return array_reduce( $functions, function ($carry, $function) { return function ($x) use ($carry, $function) { return $function($carry($x)); }; }, function ($x) { return $x; } ); }
示例
$compose = compose( // add 2 function ($x) { return $x + 2; }, // multiply 4 function ($x) { return $x * 4; } ); $compose(3); // 20
memoize
函数的缓存导致内存使用。
function memoize($func) { return function () use ($func) { static $cache = []; $args = func_get_args(); $key = serialize($args); $cached = true; if (!isset($cache[$key])) { $cache[$key] = $func(...$args); $cached = false; } return ['result' => $cache[$key], 'cached' => $cached]; }; }
示例
$memoizedAdd = memoize( function ($num) { return $num + 10; } ); var_dump($memoizedAdd(5)); // ['result' => 15, 'cached' => false] var_dump($memoizedAdd(6)); // ['result' => 16, 'cached' => false] var_dump($memoizedAdd(5)); // ['result' => 15, 'cached' => true]
curry
通过多次调用传递参数来curry一个函数。
function curry($function) { $accumulator = function ($arguments) use ($function, &$accumulator) { return function (...$args) use ($function, $arguments, $accumulator) { $arguments = array_merge($arguments, $args); $reflection = new ReflectionFunction($function); $totalArguments = $reflection->getNumberOfRequiredParameters(); if ($totalArguments <= count($arguments)) { return $function(...$arguments); } return $accumulator($arguments); }; }; return $accumulator([]); }
示例
$curriedAdd = curry( function ($a, $b) { return $a + $b; } ); $add10 = $curriedAdd(10); var_dump($add10(15)); // 25
once
仅调用一次函数。
function once($function) { return function (...$args) use ($function) { static $called = false; if ($called) { return; } $called = true; return $function(...$args); }; }
示例
$add = function ($a, $b) { return $a + $b; }; $once = once($add); var_dump($once(10, 5)); // 15 var_dump($once(20, 10)); // null
variadicFunction
可变参数函数允许你捕获传递给函数的任意数量的参数。
该函数接受任意数量的变量来执行代码。它使用for循环迭代参数。
function variadicFunction($operands) { $sum = 0; foreach($operands as $singleOperand) { $sum += $singleOperand; } return $sum; }
示例
variadicFunction([1, 2]); // 3 variadicFunction([1, 2, 3, 4]); // 10
贡献
你总是欢迎为此项目做出贡献。请阅读贡献指南。
许可
本项目采用MIT许可协议 - 请参阅许可文件以获取详细信息。