一个有用的PHP片段的集合

一个有用的PHP片段的集合,你可以在30秒或更短的时间内理解。

Table of Contents

Array

View contents * [`all`](#all) * [`any`](#any) * [`chunk`](#chunk) * [`deepFlatten`](#deepflatten) * [`drop`](#drop) * [`findLast`](#findlast) * [`findLastIndex`](#findlastindex) * [`flatten`](#flatten) * [`groupBy`](#groupby) * [`hasDuplicates`](#hasduplicates) * [`head`](#head) * [`last`](#last) * [`pluck`](#pluck) * [`pull`](#pull) * [`reject`](#reject) * [`remove`](#remove) * [`tail`](#tail) * [`take`](#take) * [`without`](#without)

Math

View contents * [`average`](#average) * [`factorial`](#factorial) * [`fibonacci`](#fibonacci) * [`gcd`](#gcd) * [`isEven`](#iseven) * [`isPrime`](#isprime) * [`lcm`](#lcm) * [`median`](#median)

String

View contents * [`endsWith`](#endswith) * [`isAnagram`](#isanagram) * [`isLowerCase`](#islowercase) * [`isUpperCase`](#isuppercase) * [`palindrome`](#palindrome) * [`startsWith`](#startswith)


Array

all

Returns true if the provided function returns true for all elements of an array, false otherwise.

function all($items, $func)
{
    return count(array_filter($items, $func)) === count($items);
}

Examples ```php all([2, 3, 4, 5], function ($item) { return $item > 1; }); // true ```

any

Returns true if the provided function returns true for at least one element of an array, false otherwise.

function any($items, $func)
{
    return count(array_filter($items, $func)) > 0;
}

Examples ```php any([1, 2, 3, 4], function ($item) { return $item < 2; }); // true ```

chunk

Chunks an array into smaller arrays of a specified size.

function chunk($items, $size)
{
    return array_chunk($items, $size);
}

Examples ```php chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]] ```

deepFlatten

Deep flattens an array.

function deepFlatten($items)
{
    $result = [];
    foreach ($items as $item) {
        if (!is_array($item)) {
            $result[] = $item;
        } else {
            $result = array_merge($result, deepFlatten($item));
        }
    }

    return $result;
}

Examples ```php deepFlatten([1, [2], [[3], 4], 5]); // [1, 2, 3, 4, 5] ```

drop

Returns a new array with n elements removed from the left.

function drop($items, $n = 1)
{
    return array_slice($items, $n);
}

Examples ```php drop([1, 2, 3]); // [2,3] drop([1, 2, 3], 2); // [3] ```

findLast

Returns the last element for which the provided function returns a truthy value.

function findLast($items, $func)
{
    $filteredItems = array_filter($items, $func);

    return array_pop($filteredItems);
}

Examples ```php findLast([1, 2, 3, 4], function ($n) { return ($n % 2) === 1; }); // 3 ```

findLastIndex

Returns the index of the last element for which the provided function returns a truthy value.

function findLastIndex($items, $func)
{
    $keys = array_keys(array_filter($items, $func));

    return array_pop($keys);
}

Examples ```php findLastIndex([1, 2, 3, 4], function ($n) { return ($n % 2) === 1; }); // 2 ```

flatten

Flattens an array up to the one level depth.

function flatten($items)
{
    $result = [];
    foreach ($items as $item) {
        if (!is_array($item)) {
            $result[] = $item;
        } else {
            $result = array_merge($result, array_values($item));
        }
    }

    return $result;
}

Examples ```php flatten([1, [2], 3, 4]); // [1, 2, 3, 4] ```

groupBy

Groups the elements of an array based on the given function.

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;
}

Examples ```php groupBy(['one', 'two', 'three'], 'strlen') // [3 => ['one', 'two'], 5 => ['three']] ```

hasDuplicates

Checks a flat list for duplicate values. Returns true if duplicate values exists and false if values are all unique.

function hasDuplicates($items)
{
    return count($items) > count(array_unique($items));
}

Examples ```php hasDuplicates([1, 2, 3, 4, 5, 5]); // true ```

head

Returns the head of a list.

function head($items)
{
    return reset($items);
}

Examples ```php head([1, 2, 3]); // 1 ```

last

Returns the last element in an array.

function last($items)
{
    return end($items);
}

Examples ```php last([1, 2, 3]); // 3 ```

pluck

Retrieves all of the values for a given key:

function pluck($items, $key)
{
    return array_map( function($item) use ($key) {
        return is_object($item) ? $item->$key : $item[$key];
    }, $items);
}

Examples ```php pluck([ ['product_id' => 'prod-100', 'name' => 'Desk'], ['product_id' => 'prod-200', 'name' => 'Chair'], ], 'name'); // ['Desk', 'Chair'] ```

pull

Mutates the original array to filter out the values specified.

function pull(&$items, ...$params)
{
    $items = array_values(array_diff($items, $params));
    return $items;
}

Examples ```php $items = ['a', 'b', 'c', 'a', 'b', 'c']; pull($items, 'a', 'c'); // $items will be ['b', 'b'] ```

reject

Filters the collection using the given callback.

function reject($items, $func)
{
    return array_values(array_diff($items, array_filter($items, $func)));
}

Examples ```php reject(['Apple', 'Pear', 'Kiwi', 'Banana'], function ($item) { return strlen($item) > 4; }); // ['Pear', 'Kiwi'] ```

remove

Removes elements from an array for which the given function returns false.

function remove($items, $func)
{
    $keys = array_keys(array_filter($items, $func));

    foreach ($keys as $key) {
        unset($items[$key]);
    }

    return $items;
}

Examples ```php remove([1, 2, 3, 4], function ($n) { return ($n % 2) === 0; }); // [0 => 1, 2 => 3] ```

tail

Returns all elements in an array except for the first one.

function tail($items)
{
    return count($items) > 1 ? array_slice($items, 1) : $items;
}

Examples ```php tail([1, 2, 3]); // [2, 3] ```

take

Returns an array with n elements removed from the beginning.

function take($items, $n = 1)
{
    return array_slice($items, 0, $n);
}

Examples ```php take([1, 2, 3], 5); // [1, 2, 3] take([1, 2, 3, 4, 5], 2); // [1, 2] ```

without

Filters out the elements of an array, that have one of the specified values.

function without($items, ...$params)
{
    return array_values(array_diff($items, $params));
}

Examples ```php without([2, 1, 2, 3], 1, 2); // [3] ```


Math

average

Returns the average of two or more numbers.

function average(...$items)
{
    return count($items) === 0 ? 0 : array_sum($items) / count($items);
}

Examples ```php average(1, 2, 3); // 2 ```

factorial

Calculates the factorial of a number.

function factorial($n)
{
    if ($n <= 1) {
        return 1;
    }

    return $n * factorial($n - 1);
}

Examples ```php factorial(6); // 720 ```

fibonacci

Generates an array, containing the Fibonacci sequence, up until the nth term.

function fibonacci($n)
{
    $sequence = [0, 1];

    for ($i = 0; $i < $n - 2; $i++) {
        array_push($sequence, array_sum(array_slice($sequence, -2, 2, true)));
    }

    return $sequence;
}

Examples ```php fibonacci(6); // [0, 1, 1, 2, 3, 5] ```

gcd

Calculates the greatest common divisor between two or more numbers.

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);
}

Examples ```php gcd(8, 36); // 4 gcd(12, 8, 32); // 4 ```

isEven

Returns true if the given number is even, false otherwise.

function isEven($number)
{
    return ($number % 2) === 0;
}

Examples ```php isEven(4); // true ```

isPrime

Checks if the provided integer is a prime number.

function isPrime($number)
{
    $boundary = floor(sqrt($number));
    for ($i = 2; $i <= $boundary; $i++) {
        if ($number % $i === 0) {
            return false;
        }
    }

    return $number >= 2;
}

Examples ```php isPrime(3); // true ```

lcm

Returns the least common multiple of two or more numbers.

function lcm(...$numbers)
{
    $ans = $numbers[0];
    for ($i = 1; $i < count($numbers); $i++) {
        $ans = ((($numbers[$i] * $ans)) / (gcd($numbers[$i], $ans)));
    }

    return $ans;
}

Examples ```php lcm(12, 7); // 84 lcm(1, 3, 4, 5); // 60 ```

median

Returns the median of an array of numbers.

function median($numbers)
{
    sort($numbers);
    $totalNumbers = count($numbers);
    $mid = floor($totalNumbers / 2);

    return ($totalNumbers % 2) === 0 ? ($numbers[$mid - 1] + $numbers[$mid]) / 2 : $numbers[$mid];
}

Examples ```php median([1, 3, 3, 6, 7, 8, 9]); // 6 median([1, 2, 3, 6, 7, 9]); // 4.5 ```


String

endsWith

Check if a string is ends with a given substring.

function endsWith($haystack, $needle)
{
    return substr($haystack, -strlen($needle)) === $needle;
}

Examples ```php endsWith('Hi, this is me', 'me'); // true ```

isAnagram

Compare two strings and returns true if both strings are anagram, false otherwise.

function isAnagram($string1, $string2)
{
    return count_chars($string1, 1) === count_chars($string2, 1);
}

Examples ```php isAnagram('act', 'cat'); // true ```

isLowerCase

Returns true if the given string is lower case, false otherwise.

function isLowerCase($string)
{
    $char = mb_substr($string, 0, 1, "UTF-8");
    return mb_strtolower($char, "UTF-8") === $char;
}

Examples ```php isLowerCase('Morning shows the day!'); // false isLowerCase('hello'); // true ```

isUpperCase

Returns true if the given string is upper case, false otherwise.

function isUpperCase($string)
{
    $char = mb_substr($string, 0, 1, "UTF-8");
    return mb_strtolower($char, "UTF-8") !== $char;
}

Examples ```php isUpperCase('Morning Shows The Day!'); // true isUpperCase('qUick Fox'); // false ```

palindrome

Returns true if the given string is a palindrome, false otherwise.

function palindrome($string)
{
    return strrev($string) === $string;
}

Examples ```php palindrome('racecar'); // true ```

startsWith

Check if a string is starts with a given substring.

function startsWith($haystack, $needle)
{
    return substr($haystack, 0, strlen($needle)) === $needle;
}

Examples ```php startsWith('Hi, this is me', 'Hi'); // true ```

Related

Contribute

You’re always welcome to contribute to this project. Please read the contribution guide.

License

This project is licensed under the MIT License - see the License File for details

(完)

原文链接

本文参与腾讯云自媒体分享计划,欢迎正在阅读的你也加入,一起分享。

发表于

我来说两句

0 条评论
登录 后参与评论

相关文章

来自专栏绿巨人专栏

Represent code in math equations

3447
来自专栏AI研习社

一次 PyTorch 的踩坑经历,以及如何避免梯度成为NaN

本文首发于知乎答主小磊在「PyTorch有哪些坑/bug?」下的回答,AI 研习社获原作者授权转载。 分享一下我最近的踩坑经历吧。 这几天在实现一个语义分割的 ...

5956

使用OpenCV,Python和模板匹配来播放“Waldo在哪里?”

这是一篇来自PyImageSearch的Adrian Rosebrock的博客,他的博客内容包括计算机视觉,图像处理和建筑图像搜索引擎等。

2226
来自专栏思考的代码世界

Python网络数据采集之处理自然语言|第07天

在之前我们了解了如何把文本内容分解成 n-gram 模型,或者说是n个单词长度的词组。从最基本的功能上说,这个集合可以用来确定这段文字中最常用的单词和短语。另外...

3407
来自专栏郭耀华‘s Blog

LeetCode第四天

leetcode 第四天 2018年1月4日 15.(628)Maximum Product of Three Numbers ? JAVA class Sol...

2945
来自专栏Jerry的SAP技术分享

Jerry的通过CDS view + Smart Template 开发Fiori应用的blog合集

S4/HANA里有一个新的UI框架叫做Smart template, 配合ABAP后台的CDS view技术,能够让developer以Metadata dri...

1948
来自专栏CreateAMind

NIPS的最佳论文 强化学习Value iteration Network 及代码

TensorFlow实现:https://github.com/TheAbhiKumar/tensorflow-value-iteration-networks

1052
来自专栏calmound

Maya

建立酒杯的方法(CV曲线) surface(曲面)-- creat cv curve tool-- control vertex(调整图形)[再次creat c...

3818
来自专栏AI研习社

Github 项目推荐 | PyTorch 文本工具库/数据集

PyTorch-NLP,简称 torchnlp,是一个神经网络层、文本处理模块和数据集库,旨在加速自然语言处理的研究。

1152
来自专栏量化投资与机器学习

【代码+论文】通过ML、Time Series模型学习股价行为

今天编辑部给大家带来的是来自Jeremy Jordan的论文,主要分析论文的建模步骤和方法,具体内容大家可以自行查看。 # Standard imports i...

3528

扫码关注云+社区