PHP code example of nguyenanhung / 30-seconds-of-php-code

1. Go to this page and download the library: Download nguyenanhung/30-seconds-of-php-code library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

nguyenanhung / 30-seconds-of-php-code example snippets


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

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

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

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

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

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

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]

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

drop([1, 2, 3]); // [2,3]
drop([1, 2, 3], 2); // [3]

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

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

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]

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']]

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

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

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

head([1, 2, 3]); // 1

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

last([1, 2, 3]); // 3

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']

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']

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']

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]

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

tail([1, 2, 3]); // [2, 3]

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]

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

without([2, 1, 2, 3], 1, 2); // [3]

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']]

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

average(1, 2, 3); // 2

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

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

factorial(6); // 720

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]

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

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

isEven(4); // true

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

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

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

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

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

function approximatelyEqual($number1, $number2, $epsilon = 0.001)
{
    return abs($number1 - $number2) < $epsilon;
}

approximatelyEqual(10.0, 10.00001); // true

approximatelyEqual(10.0, 10.01); // false

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

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

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

function firstStringBetween($haystack, $start, $end)
{
    return trim(strstr(strstr($haystack, $start), $end, true), $start . $end);
}

firstStringBetween('This is a [custom] string', '[', ']'); // custom

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

isAnagram('act', 'cat'); // true

function isLowerCase($string)
{
    return $string === strtolower($string);
}

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

function isUpperCase($string)
{
    return $string === strtoupper($string);
}

isUpperCase('MORNING SHOWS THE DAY!'); // true
isUpperCase('qUick Fox'); // false

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

palindrome('racecar'); // true
palindrome(2221222); // true

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

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

function countVowels($string)
{
    preg_match_all('/[aeiou]/i', $string, $matches);

    return count($matches[0]);
}

countVowels('sampleInput'); // 4

function decapitalize($string, $upperRest = false)
{
    return lcfirst($upperRest ? strtoupper($string) : $string);
}

decapitalize('FooBar'); // 'fooBar'

function isContains($string, $needle)
{
    return strpos($string, $needle);
}

isContains('This is an example string', 'example'); // true

isContains('This is an example string', 'hello'); // false

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

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]

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

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

function variadicFunction($operands)
{
    $sum = 0;
    foreach($operands as $singleOperand) {
        $sum += $singleOperand;
    }
    return $sum;
}

variadicFunction([1, 2]); // 3
variadicFunction([1, 2, 3, 4]); // 10