{"id":15309569,"url":"https://github.com/nguyenanhung/30-seconds-of-php-code","last_synced_at":"2025-04-09T05:44:20.391Z","repository":{"id":57026394,"uuid":"155322221","full_name":"nguyenanhung/30-seconds-of-php-code","owner":"nguyenanhung","description":"A curated collection of useful PHP snippets that you can understand in 30 seconds or less.","archived":false,"fork":false,"pushed_at":"2025-01-21T10:55:35.000Z","size":107,"stargazers_count":1,"open_issues_count":0,"forks_count":1,"subscribers_count":0,"default_branch":"master","last_synced_at":"2025-04-06T06:48:41.465Z","etag":null,"topics":["array","functions","helper","match","string","string-manipulation","support","text-helper","xml-converter"],"latest_commit_sha":null,"homepage":"","language":"PHP","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/nguyenanhung.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2018-10-30T04:01:12.000Z","updated_at":"2025-01-21T10:55:14.000Z","dependencies_parsed_at":"2022-08-23T16:20:34.511Z","dependency_job_id":null,"html_url":"https://github.com/nguyenanhung/30-seconds-of-php-code","commit_stats":null,"previous_names":[],"tags_count":16,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nguyenanhung%2F30-seconds-of-php-code","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nguyenanhung%2F30-seconds-of-php-code/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nguyenanhung%2F30-seconds-of-php-code/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/nguyenanhung%2F30-seconds-of-php-code/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/nguyenanhung","download_url":"https://codeload.github.com/nguyenanhung/30-seconds-of-php-code/tar.gz/refs/heads/master","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":247987107,"owners_count":21028891,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["array","functions","helper","match","string","string-manipulation","support","text-helper","xml-converter"],"created_at":"2024-10-01T08:24:33.988Z","updated_at":"2025-04-09T05:44:20.369Z","avatar_url":"https://github.com/nguyenanhung.png","language":"PHP","funding_links":[],"categories":[],"sub_categories":[],"readme":"![Logo](/logo.png)\n\n# 30 seconds of php code\n\u003e A curated collection of useful PHP snippets that you can understand in 30 seconds or less.\n\nNote: This project is inspired by [30 Seconds of Code](https://github.com/Chalarangelo/30-seconds-of-code), but there is no affiliation with that project.\n\n## Table of Contents\n\n### 📚 Array\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`all`](#all)\n* [`any`](#any)\n* [`chunk`](#chunk)\n* [`deepFlatten`](#deepflatten)\n* [`drop`](#drop)\n* [`findLast`](#findlast)\n* [`findLastIndex`](#findlastindex)\n* [`flatten`](#flatten)\n* [`groupBy`](#groupby)\n* [`hasDuplicates`](#hasduplicates)\n* [`head`](#head)\n* [`last`](#last)\n* [`pluck`](#pluck)\n* [`pull`](#pull)\n* [`reject`](#reject)\n* [`remove`](#remove)\n* [`tail`](#tail)\n* [`take`](#take)\n* [`without`](#without)\n* [`orderBy`](#orderby)\n\n\u003c/details\u003e\n\n### ➗ Math\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`average`](#average)\n* [`factorial`](#factorial)\n* [`fibonacci`](#fibonacci)\n* [`gcd`](#gcd)\n* [`isEven`](#iseven)\n* [`isPrime`](#isprime)\n* [`lcm`](#lcm)\n* [`median`](#median)\n* [`maxN`](#maxn)\n* [`minN`](#minn)\n* [`approximatelyEqual`](#approximatelyequal)\n* [`clampNumber`](#clampnumber)\n\n\u003c/details\u003e\n\n### 📜 String\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`endsWith`](#endswith)\n* [`firstStringBetween`](#firststringbetween)\n* [`isAnagram`](#isanagram)\n* [`isLowerCase`](#islowercase)\n* [`isUpperCase`](#isuppercase)\n* [`palindrome`](#palindrome)\n* [`startsWith`](#startswith)\n* [`countVowels`](#countvowels)\n* [`decapitalize`](#decapitalize)\n* [`isContains`](#iscontains)\n\n\u003c/details\u003e\n\n### 🎛️ Function\n\n\u003cdetails\u003e\n\u003csummary\u003eView contents\u003c/summary\u003e\n\n* [`compose`](#compose)\n* [`memoize`](#memoize)\n* [`curry`](#curry)\n* [`once`](#once)\n* [`variadicFunction`](#variadicfunction)\n\n\u003c/details\u003e\n\n---\n ## 📚 Array\n\n### all\nReturns `true` if the provided function returns `true` for all elements of an array, `false` otherwise.\n\n```php\nfunction all($items, $func)\n{\n    return count(array_filter($items, $func)) === count($items);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nall([2, 3, 4, 5], function ($item) {\n    return $item \u003e 1;\n}); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### any\nReturns `true` if the provided function returns `true` for at least one element of an array, `false` otherwise.\n\n```php\nfunction any($items, $func)\n{\n    return count(array_filter($items, $func)) \u003e 0;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nany([1, 2, 3, 4], function ($item) {\n    return $item \u003c 2;\n}); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### chunk\nChunks an array into smaller arrays of a specified size.\n\n```php\nfunction chunk($items, $size)\n{\n    return array_chunk($items, $size);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nchunk([1, 2, 3, 4, 5], 2); // [[1, 2], [3, 4], [5]]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### deepFlatten\nDeep flattens an array.\n\n```php\nfunction deepFlatten($items)\n{\n    $result = [];\n    foreach ($items as $item) {\n        if (!is_array($item)) {\n            $result[] = $item;\n        } else {\n            $result = array_merge($result, deepFlatten($item));\n        }\n    }\n\n    return $result;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\ndeepFlatten([1, [2], [[3], 4], 5]); // [1, 2, 3, 4, 5]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### drop\nReturns a new array with `n` elements removed from the left.\n\n```php\nfunction drop($items, $n = 1)\n{\n    return array_slice($items, $n);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\ndrop([1, 2, 3]); // [2,3]\ndrop([1, 2, 3], 2); // [3]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### findLast\nReturns the last element for which the provided function returns a truthy value.\n\n```php\nfunction findLast($items, $func)\n{\n    $filteredItems = array_filter($items, $func);\n\n    return array_pop($filteredItems);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nfindLast([1, 2, 3, 4], function ($n) {\n    return ($n % 2) === 1;\n});\n// 3\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### findLastIndex\nReturns the index of the last element for which the provided function returns a truthy value.\n\n```php\nfunction findLastIndex($items, $func)\n{\n    $keys = array_keys(array_filter($items, $func));\n\n    return array_pop($keys);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nfindLastIndex([1, 2, 3, 4], function ($n) {\n    return ($n % 2) === 1;\n});\n// 2\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### flatten\nFlattens an array up to the one level depth.\n\n```php\nfunction flatten($items)\n{\n    $result = [];\n    foreach ($items as $item) {\n        if (!is_array($item)) {\n            $result[] = $item;\n        } else {\n            $result = array_merge($result, array_values($item));\n        }\n    }\n\n    return $result;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nflatten([1, [2], 3, 4]); // [1, 2, 3, 4]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### groupBy\nGroups the elements of an array based on the given function.\n\n```php\nfunction groupBy($items, $func)\n{\n    $group = [];\n    foreach ($items as $item) {\n        if ((!is_string($func) \u0026\u0026 is_callable($func)) || function_exists($func)) {\n            $key = call_user_func($func, $item);\n            $group[$key][] = $item;\n        } elseif (is_object($item)) {\n            $group[$item-\u003e{$func}][] = $item;\n        } elseif (isset($item[$func])) {\n            $group[$item[$func]][] = $item;\n        }\n    }\n\n    return $group;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\ngroupBy(['one', 'two', 'three'], 'strlen'); // [3 =\u003e ['one', 'two'], 5 =\u003e ['three']]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### hasDuplicates\nChecks a flat list for duplicate values. Returns `true` if duplicate values exists and `false` if values are all unique.\n\n```php\nfunction hasDuplicates($items)\n{\n    return count($items) \u003e count(array_unique($items));\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nhasDuplicates([1, 2, 3, 4, 5, 5]); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### head\nReturns the head of a list.\n\n```php\nfunction head($items)\n{\n    return reset($items);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nhead([1, 2, 3]); // 1\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### last\nReturns the last element in an array.\n\n```php\nfunction last($items)\n{\n    return end($items);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nlast([1, 2, 3]); // 3\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### pluck\nRetrieves all of the values for a given key:\n\n```php\nfunction pluck($items, $key)\n{\n    return array_map( function($item) use ($key) {\n        return is_object($item) ? $item-\u003e$key : $item[$key];\n    }, $items);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\npluck([\n    ['product_id' =\u003e 'prod-100', 'name' =\u003e 'Desk'],\n    ['product_id' =\u003e 'prod-200', 'name' =\u003e 'Chair'],\n], 'name');\n// ['Desk', 'Chair']\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### pull\nMutates the original array to filter out the values specified.\n\n```php\nfunction pull(\u0026$items, ...$params)\n{\n    $items = array_values(array_diff($items, $params));\n    return $items;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\n$items = ['a', 'b', 'c', 'a', 'b', 'c'];\npull($items, 'a', 'c'); // $items will be ['b', 'b']\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### reject\nFilters the collection using the given callback.\n\n```php\nfunction reject($items, $func)\n{\n    return array_values(array_diff($items, array_filter($items, $func)));\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nreject(['Apple', 'Pear', 'Kiwi', 'Banana'], function ($item) {\n    return strlen($item) \u003e 4;\n}); // ['Pear', 'Kiwi']\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### remove\nRemoves elements from an array for which the given function returns false.\n\n```php\nfunction remove($items, $func)\n{\n    $filtered = array_filter($items, $func);\n\n    return array_diff_key($items, $filtered);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nremove([1, 2, 3, 4], function ($n) {\n    return ($n % 2) === 0;\n});\n// [0 =\u003e 1, 2 =\u003e 3]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### tail\nReturns all elements in an array except for the first one.\n\n```php\nfunction tail($items)\n{\n    return count($items) \u003e 1 ? array_slice($items, 1) : $items;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\ntail([1, 2, 3]); // [2, 3]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### take\nReturns an array with n elements removed from the beginning.\n\n```php\nfunction take($items, $n = 1)\n{\n    return array_slice($items, 0, $n);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\ntake([1, 2, 3], 5); // [1, 2, 3]\ntake([1, 2, 3, 4, 5], 2); // [1, 2]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### without\nFilters out the elements of an array, that have one of the specified values.\n\n```php\nfunction without($items, ...$params)\n{\n    return array_values(array_diff($items, $params));\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nwithout([2, 1, 2, 3], 1, 2); // [3]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### orderBy\n\nSorts a collection of arrays or objects by key.\n\n```php\nfunction orderBy($items, $attr, $order)\n{\n    $sortedItems = [];\n    foreach ($items as $item) {\n        $key = is_object($item) ? $item-\u003e{$attr} : $item[$attr];\n        $sortedItems[$key] = $item;\n    }\n    if ($order === 'desc') {\n        krsort($sortedItems);\n    } else {\n        ksort($sortedItems);\n    }\n\n    return array_values($sortedItems);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\norderBy(\n    [\n        ['id' =\u003e 2, 'name' =\u003e 'Joy'],\n        ['id' =\u003e 3, 'name' =\u003e 'Khaja'],\n        ['id' =\u003e 1, 'name' =\u003e 'Raja']\n    ],\n    'id',\n    'desc'\n); // [['id' =\u003e 3, 'name' =\u003e 'Khaja'], ['id' =\u003e 2, 'name' =\u003e 'Joy'], ['id' =\u003e 1, 'name' =\u003e 'Raja']]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n\n---\n ## ➗ Math\n\n### average\nReturns the average of two or more numbers.\n\n```php\nfunction average(...$items)\n{\n    return count($items) === 0 ? 0 : array_sum($items) / count($items);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\naverage(1, 2, 3); // 2\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### factorial\nCalculates the factorial of a number.\n\n```php\nfunction factorial($n)\n{\n    if ($n \u003c= 1) {\n        return 1;\n    }\n\n    return $n * factorial($n - 1);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nfactorial(6); // 720\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### fibonacci\nGenerates an array, containing the Fibonacci sequence, up until the nth term.\n\n```php\nfunction fibonacci($n)\n{\n    $sequence = [0, 1];\n\n    for ($i = 2; $i \u003c $n; $i++) {\n        $sequence[$i] = $sequence[$i-1] + $sequence[$i-2];\n    }\n\n    return $sequence;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nfibonacci(6); // [0, 1, 1, 2, 3, 5]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### gcd\nCalculates the greatest common divisor between two or more numbers.\n\n```php\nfunction gcd(...$numbers)\n{\n    if (count($numbers) \u003e 2) {\n        return array_reduce($numbers, 'gcd');\n    }\n\n    $r = $numbers[0] % $numbers[1];\n    return $r === 0 ? abs($numbers[1]) : gcd($numbers[1], $r);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\ngcd(8, 36); // 4\ngcd(12, 8, 32); // 4\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### isEven\nReturns `true` if the given number is even, `false` otherwise.\n\n```php\nfunction isEven($number)\n{\n    return ($number % 2) === 0;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nisEven(4); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### isPrime\nChecks if the provided integer is a prime number.\n\n```php\nfunction isPrime($number)\n{\n    $boundary = floor(sqrt($number));\n    for ($i = 2; $i \u003c= $boundary; $i++) {\n        if ($number % $i === 0) {\n            return false;\n        }\n    }\n\n    return $number \u003e= 2;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nisPrime(3); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### lcm\nReturns the least common multiple of two or more numbers.\n\n```php\nfunction lcm(...$numbers)\n{\n    $ans = $numbers[0];\n    for ($i = 1; $i \u003c count($numbers); $i++) {\n        $ans = ((($numbers[$i] * $ans)) / (gcd($numbers[$i], $ans)));\n    }\n\n    return $ans;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nlcm(12, 7); // 84\nlcm(1, 3, 4, 5); // 60\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### median\nReturns the median of an array of numbers.\n\n```php\nfunction median($numbers)\n{\n    sort($numbers);\n    $totalNumbers = count($numbers);\n    $mid = floor($totalNumbers / 2);\n\n    return ($totalNumbers % 2) === 0 ? ($numbers[$mid - 1] + $numbers[$mid]) / 2 : $numbers[$mid];\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nmedian([1, 3, 3, 6, 7, 8, 9]); // 6\nmedian([1, 2, 3, 6, 7, 9]); // 4.5\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### maxN\nReturns the n maximum elements from the provided array.\n\n```php\nfunction maxN($numbers)\n{\n    $maxValue = max($numbers);\n    $maxValueArray = array_filter($numbers, function ($value) use ($maxValue) {\n        return $maxValue === $value;\n    });\n\n    return count($maxValueArray);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nmaxN([1, 2, 3, 4, 5, 5]); // 2\nmaxN([1, 2, 3, 4, 5]); // 1\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### minN\nReturns the n minimum elements from the provided array.\n\n```php\nfunction minN($numbers)\n{\n    $minValue = min($numbers);\n    $minValueArray = array_filter($numbers, function ($value) use ($minValue) {\n        return $minValue === $value;\n    });\n\n    return count($minValueArray);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nminN([1, 1, 2, 3, 4, 5, 5]); // 2\nminN([1, 2, 3, 4, 5]); // 1\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### approximatelyEqual\n\nChecks if two numbers are approximately equal to each other.\n\nUse abs() to compare the absolute difference of the two values to epsilon. Omit the third parameter, epsilon, to use a default value of 0.001.\n\n```php\nfunction approximatelyEqual($number1, $number2, $epsilon = 0.001)\n{\n    return abs($number1 - $number2) \u003c $epsilon;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\napproximatelyEqual(10.0, 10.00001); // true\n\napproximatelyEqual(10.0, 10.01); // false\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### clampNumber\n\nClamps num within the inclusive range specified by the boundary values a and b.\n\nIf num falls within the range, return num. Otherwise, return the nearest number in the range.\n\n```php\nfunction clampNumber($num, $a, $b)\n{\n    return max(min($num, max($a, $b)), min($a, $b));\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nclampNumber(2, 3, 5); // 3\nclampNumber(1, -1, -5); // -1\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n\n---\n ## 📜 String\n\n### endsWith\n\nCheck if a string is ends with a given substring.\n\n```php\nfunction endsWith($haystack, $needle)\n{\n    return strrpos($haystack, $needle) === (strlen($haystack) - strlen($needle));\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nendsWith('Hi, this is me', 'me'); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### firstStringBetween\n\nReturns the first string there is between the strings from the parameter start and end.\n\n```php\nfunction firstStringBetween($haystack, $start, $end)\n{\n    return trim(strstr(strstr($haystack, $start), $end, true), $start . $end);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nfirstStringBetween('This is a [custom] string', '[', ']'); // custom\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### isAnagram\n\nCompare two strings and returns `true` if both strings are anagram, `false` otherwise.\n\n```php\nfunction isAnagram($string1, $string2)\n{\n    return count_chars($string1, 1) === count_chars($string2, 1);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nisAnagram('act', 'cat'); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### isLowerCase\n\nReturns `true` if the given string is lower case, `false` otherwise.\n\n```php\nfunction isLowerCase($string)\n{\n    return $string === strtolower($string);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nisLowerCase('Morning shows the day!'); // false\nisLowerCase('hello'); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### isUpperCase\n\nReturns `true` if the given string is upper case, false otherwise.\n\n```php\nfunction isUpperCase($string)\n{\n    return $string === strtoupper($string);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nisUpperCase('MORNING SHOWS THE DAY!'); // true\nisUpperCase('qUick Fox'); // false\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### palindrome\n\nReturns `true` if the given string is a palindrome, `false` otherwise.\n\n```php\nfunction palindrome($string)\n{\n    return strrev($string) === (string) $string;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\npalindrome('racecar'); // true\npalindrome(2221222); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### startsWith\n\nCheck if a string starts with a given substring.\n\n```php\nfunction startsWith($haystack, $needle)\n{\n    return strpos($haystack, $needle) === 0;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nstartsWith('Hi, this is me', 'Hi'); // true\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### countVowels\n\nReturns number of vowels in provided string.\n\nUse a regular expression to count the number of vowels (A, E, I, O, U) in a string.\n\n```php\nfunction countVowels($string)\n{\n    preg_match_all('/[aeiou]/i', $string, $matches);\n\n    return count($matches[0]);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\ncountVowels('sampleInput'); // 4\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### decapitalize\n\nDecapitalizes the first letter of a string.\n\nDecapitalizes the first letter of the string and then adds it with rest of the string. Omit the ```upperRest``` parameter to keep the rest of the string intact, or set it to ```true``` to convert to uppercase.\n\n```php\nfunction decapitalize($string, $upperRest = false)\n{\n    return lcfirst($upperRest ? strtoupper($string) : $string);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\ndecapitalize('FooBar'); // 'fooBar'\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### isContains\n\nCheck if a word / substring exist in a given string input.\nUsing `strpos` to find the position of the first occurrence of a substring in a string. Returns either `true` or `false`\n```php\nfunction isContains($string, $needle)\n{\n    return strpos($string, $needle);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nisContains('This is an example string', 'example'); // true\n```\n```php\nisContains('This is an example string', 'hello'); // false\n```\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n\n---\n ## 🎛️ Function\n\n### compose\n\nReturn a new function that composes multiple functions into a single callable.\n\n```php\nfunction compose(...$functions)\n{\n    return array_reduce(\n        $functions,\n        function ($carry, $function) {\n            return function ($x) use ($carry, $function) {\n                return $function($carry($x));\n            };\n        },\n        function ($x) {\n            return $x;\n        }\n    );\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\n$compose = compose(\n    // add 2\n    function ($x) {\n        return $x + 2;\n    },\n    // multiply 4\n    function ($x) {\n        return $x * 4;\n    }\n);\n$compose(3); // 20\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### memoize\n\nMemoization of a function results in memory.\n\n```php\nfunction memoize($func)\n{\n    return function () use ($func) {\n        static $cache = [];\n\n        $args = func_get_args();\n        $key = serialize($args);\n        $cached = true;\n\n        if (!isset($cache[$key])) {\n            $cache[$key] = $func(...$args);\n            $cached = false;\n        }\n\n        return ['result' =\u003e $cache[$key], 'cached' =\u003e $cached];\n    };\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\n$memoizedAdd = memoize(\n    function ($num) {\n        return $num + 10;\n    }\n);\n\nvar_dump($memoizedAdd(5)); // ['result' =\u003e 15, 'cached' =\u003e false]\nvar_dump($memoizedAdd(6)); // ['result' =\u003e 16, 'cached' =\u003e false]\nvar_dump($memoizedAdd(5)); // ['result' =\u003e 15, 'cached' =\u003e true]\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### curry\n\nCurries a function to take arguments in multiple calls.\n\n```php\nfunction curry($function)\n{\n    $accumulator = function ($arguments) use ($function, \u0026$accumulator) {\n        return function (...$args) use ($function, $arguments, $accumulator) {\n            $arguments = array_merge($arguments, $args);\n            $reflection = new ReflectionFunction($function);\n            $totalArguments = $reflection-\u003egetNumberOfRequiredParameters();\n\n            if ($totalArguments \u003c= count($arguments)) {\n                return $function(...$arguments);\n            }\n\n            return $accumulator($arguments);\n        };\n    };\n\n    return $accumulator([]);\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\n$curriedAdd = curry(\n    function ($a, $b) {\n        return $a + $b;\n    }\n);\n\n$add10 = $curriedAdd(10);\nvar_dump($add10(15)); // 25\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### once\n\nCall a function only once.\n\n```php\nfunction once($function)\n{\n    return function (...$args) use ($function) {\n        static $called = false;\n        if ($called) {\n            return;\n        }\n        $called = true;\n        return $function(...$args);\n    };\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\n$add = function ($a, $b) {\n    return $a + $b;\n};\n\n$once = once($add);\n\nvar_dump($once(10, 5)); // 15\nvar_dump($once(20, 10)); // null\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n### variadicFunction\n\nVariadic functions allows you to capture a variable number of arguments to a function.\n\nThe function accepts any number of variables to execute the code. It uses a for loop to iterate over the parameters.\n\n```php\nfunction variadicFunction($operands)\n{\n    $sum = 0;\n    foreach($operands as $singleOperand) {\n        $sum += $singleOperand;\n    }\n    return $sum;\n}\n```\n\n\u003cdetails\u003e\n\u003csummary\u003eExamples\u003c/summary\u003e\n\n```php\nvariadicFunction([1, 2]); // 3\nvariadicFunction([1, 2, 3, 4]); // 10\n```\n\n\u003c/details\u003e\n\n\u003cbr\u003e[⬆ Back to top](#table-of-contents)\n\n## Contribute\nYou're always welcome to contribute to this project. Please read the [contribution guide](CONTRIBUTING.md).\n\n## License\n\nThis project is licensed under the MIT License - see the [License File](LICENSE) for details\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnguyenanhung%2F30-seconds-of-php-code","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fnguyenanhung%2F30-seconds-of-php-code","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fnguyenanhung%2F30-seconds-of-php-code/lists"}