Coder Social home page Coder Social logo

twocngdagz / 30-seconds-of-php-code Goto Github PK

View Code? Open in Web Editor NEW

This project forked from chalarangelo/30-seconds-of-php

0.0 2.0 1.0 90 KB

A curated collection of useful PHP snippets that you can understand in 30 seconds or less.

License: MIT License

Shell 5.55% PHP 94.45%

30-seconds-of-php-code's Introduction

Logo

30 seconds of php code

A curated collection of useful PHP snippets that you can understand in 30 seconds or less.

Table of Contents

📚 Array

View contents

➗ Math

View contents

📜 String

View contents

🎛️ Function

View contents

📚 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
all([2, 3, 4, 5], function ($item) {
    return $item > 1;
}); // true


⬆ Back to top

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
any([1, 2, 3, 4], function ($item) {
    return $item < 2;
}); // true


⬆ Back to top

chunk

Chunks an array into smaller arrays of a specified size.

function chunk($items, $size)
{
    return array_chunk($items, $size);
}
Examples
chunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]


⬆ Back to top

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
deepFlatten([1, [2], [[3], 4], 5]); // [1, 2, 3, 4, 5]


⬆ Back to top

drop

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

function drop($items, $n = 1)
{
    return array_slice($items, $n);
}
Examples
drop([1, 2, 3]); // [2,3]
drop([1, 2, 3], 2); // [3]


⬆ Back to top

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
findLast([1, 2, 3, 4], function ($n) {
    return ($n % 2) === 1;
});
// 3


⬆ Back to top

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
findLastIndex([1, 2, 3, 4], function ($n) {
    return ($n % 2) === 1;
});
// 2


⬆ Back to top

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
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]


⬆ Back to top

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
groupBy(['one', 'two', 'three'], 'strlen') // [3 => ['one', 'two'], 5 => ['three']]


⬆ Back to top

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
hasDuplicates([1, 2, 3, 4, 5, 5]); // true


⬆ Back to top

head

Returns the head of a list.

function head($items)
{
    return reset($items);
}
Examples
head([1, 2, 3]); // 1


⬆ Back to top

last

Returns the last element in an array.

function last($items)
{
    return end($items);
}
Examples
last([1, 2, 3]); // 3


⬆ Back to top

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
pluck([
    ['product_id' => 'prod-100', 'name' => 'Desk'],
    ['product_id' => 'prod-200', 'name' => 'Chair'],
], 'name');
// ['Desk', 'Chair']


⬆ Back to top

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
$items = ['a', 'b', 'c', 'a', 'b', 'c'];
pull($items, 'a', 'c'); // $items will be ['b', 'b']


⬆ Back to top

reject

Filters the collection using the given callback.

function reject($items, $func)
{
    return array_values(array_diff($items, array_filter($items, $func)));
}
Examples
reject(['Apple', 'Pear', 'Kiwi', 'Banana'], function ($item) {
    return strlen($item) > 4;
}); // ['Pear', 'Kiwi']


⬆ Back to top

remove

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

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

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


⬆ Back to top

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
tail([1, 2, 3]); // [2, 3]


⬆ Back to top

take

Returns an array with n elements removed from the beginning.

function take($items, $n = 1)
{
    return array_slice($items, 0, $n);
}
Examples
take([1, 2, 3], 5); // [1, 2, 3]
take([1, 2, 3, 4, 5], 2); // [1, 2]


⬆ Back to top

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
without([2, 1, 2, 3], 1, 2); // [3]


⬆ Back to top


➗ Math

average

Returns the average of two or more numbers.

function average(...$items)
{
    return count($items) === 0 ? 0 : array_sum($items) / count($items);
}
Examples
average(1, 2, 3); // 2


⬆ Back to top

factorial

Calculates the factorial of a number.

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

    return $n * factorial($n - 1);
}
Examples
factorial(6); // 720


⬆ Back to top

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
fibonacci(6); // [0, 1, 1, 2, 3, 5]


⬆ Back to top

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
gcd(8, 36); // 4
gcd(12, 8, 32); // 4


⬆ Back to top

isEven

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

function isEven($number)
{
    return ($number % 2) === 0;
}
Examples
isEven(4); // true


⬆ Back to top

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
isPrime(3); // true


⬆ Back to top

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
lcm(12, 7); // 84
lcm(1, 3, 4, 5); // 60


⬆ Back to top

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
median([1, 3, 3, 6, 7, 8, 9]); // 6
median([1, 2, 3, 6, 7, 9]); // 4.5


⬆ Back to top


📜 String

endsWith

Check if a string is ends with a given substring.

function endsWith($haystack, $needle)
{
    return substr($haystack, -strlen($needle)) === $needle;
}
Examples
endsWith('Hi, this is me', 'me'); // true


⬆ Back to top

firstStringBetween

Returns the first string there is between the strings from the parameter start and end.

function firstStringBetween($haystack, $start, $end)
{
    $char = strpos($haystack, $start);
    if (!$char) {
        return '';
    }

    $char += strlen($start);
    $len = strpos($haystack, $end, $char) - $char;

    return substr($haystack, $char, $len);
}
Examples
firstStringBetween('This is a [custom] string', '[', ']'); // custom


⬆ Back to top

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
isAnagram('act', 'cat'); // true


⬆ Back to top

isLowerCase

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

function isLowerCase($string)
{
    return $string === strtolower($string);
}
Examples
isLowerCase('Morning shows the day!'); // false
isLowerCase('hello'); // true


⬆ Back to top

isUpperCase

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

function isUpperCase($string)
{
    return $string === strtoupper($string);
}
Examples
isUpperCase('MORNING SHOWS THE DAY!'); // true
isUpperCase('qUick Fox'); // false


⬆ Back to top

palindrome

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

function palindrome($string)
{
    return strrev($string) === $string;
}
Examples
palindrome('racecar'); // true


⬆ Back to top

startsWith

Check if a string is starts with a given substring.

function startsWith($haystack, $needle)
{
    return substr($haystack, 0, strlen($needle)) === $needle;
}
Examples
startsWith('Hi, this is me', 'Hi'); // true


⬆ Back to top


🎛️ Function

compose

Return a new function that composes multiple functions into a single callable.

function compose(...$functions)
{
    return array_reduce(
        $functions,
        function ($carry, $function) {
            return function ($x) use ($carry, $function) {
                return $function($carry($x));
            };
        },
        function ($x) {
            return $x;
        }
    );
}
Examples
$compose = compose(
    // add 2
    function ($x) {
        return $x + 2;
    },
    // multiply 4
    function ($x) {
        return $x * 4;
    }
);
$compose(3); // 20


⬆ Back to top

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

30-seconds-of-php-code's People

Contributors

bueltge avatar matiit avatar peter279k avatar sohelamin avatar tamimibrahim17 avatar tfrommen avatar

Watchers

 avatar  avatar

Forkers

michael-abebe

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.