分享一些實(shí)用的PHP函數(shù)(對比js/ts實(shí)現(xiàn),附代碼)
檢查數(shù)組所有元素是否滿足給定條件
如果提供的函數(shù)對數(shù)組的所有元素返回 true,則返回 true,否則返回 false。
思路
實(shí)現(xiàn)思路如下:
使用數(shù)組的filter方法對數(shù)組執(zhí)行給定的函數(shù),然后使用count方法獲取執(zhí)行后的結(jié)果,再和count方法獲取未執(zhí)行filter方法的結(jié)果進(jìn)行比較。
代碼實(shí)現(xiàn)
下面我們來看php和js以及ts代碼的實(shí)現(xiàn):
php代碼實(shí)現(xiàn)
function all($arr,$fn){
return count(array_filter($arr,$fn)) === count($arr);
}使用示例
all([2, 3, 4, 5], function ($item) {
return $item > 1;
}); // truejs代碼實(shí)現(xiàn)
const all = (arr,fn) => arr.filter(fn).length === arr.length;
ts代碼實(shí)現(xiàn)
const all = <T,U>(arr:T[], fn: (value: T, index: number, array: T[]) => U) => arr.filter(fn).length === arr.length;
使用示例
all([2,3,4,5],n => n > 1); // true
總結(jié)
與js/ts實(shí)現(xiàn)不同點(diǎn)如下:
- php通過
count方法來獲取數(shù)組的長度,而js/ts則可以直接通過length來獲取數(shù)組的長度。 - php的
filter方法名叫array_filter,而js/ts則是叫filter。
檢查數(shù)組所有元素是否有一項(xiàng)滿足給定條件
如果提供的函數(shù)對數(shù)組的至少一個(gè)元素返回 true,則返回 true,否則返回 false。
實(shí)現(xiàn)思路
實(shí)現(xiàn)思路和前面的all函數(shù)很相似,只不過這里不需要做比較,只需要判斷長度大于0即可。
代碼實(shí)現(xiàn)
下面我們來看php和js以及ts代碼的實(shí)現(xiàn):
php代碼實(shí)現(xiàn)
function any($arr,$fn){
return count(array_filter($arr,$fn)) > 0;
}使用示例
any([2, 3, 4, 5], function ($item) {
return $item < 3;
}); // truejs代碼實(shí)現(xiàn)
const any = (arr,fn) => arr.filter(fn).length > 0;
ts代碼實(shí)現(xiàn)
const any = <T,U>(arr:T[], fn: (value: T, index: number, array: T[]) => U) => arr.filter(fn).length > 0;
使用示例
any([2,3,4,5],n => n < 3); // true
總結(jié)
與all的總結(jié)一致。
檢查 2 個(gè)數(shù)字是否大致相等
檢查兩個(gè)數(shù)字是否大致相等。
實(shí)現(xiàn)思路
實(shí)現(xiàn)思路如下:
該函數(shù)有3個(gè)參數(shù),通過abs方法計(jì)算前面2個(gè)參數(shù)的絕對差值,然后與第三個(gè)參數(shù)進(jìn)行比較,判斷是否小于第三個(gè)參數(shù),第三個(gè)參數(shù)默認(rèn)值是0.001。
代碼實(shí)現(xiàn)
下面我們來看php和js以及ts代碼的實(shí)現(xiàn):
php代碼實(shí)現(xiàn)
function apprEqual($a,$b,$c = 0.001){
return abs($a - $b) < $c;
}使用示例
apprEqual(10.0, 10.00001); // true apprEqual(10.0, 10.01); // false
js代碼實(shí)現(xiàn)
const apprEqual = (a,b,c = 0.001) => Math.abs(a - b) < c;
ts代碼實(shí)現(xiàn)
const apprEqual = (a: number,b:number,c = 0.001) => Math.abs(a - b) < c;
使用示例
apprEqual(10.0, 10.00001); // true apprEqual(10.0, 10.01); // false
總結(jié)
與js/ts實(shí)現(xiàn)不同點(diǎn)如下:
- php的獲取絕對值的方法名叫
abs,而js/ts則是從Math對象中獲取,即Math.abs。
平均值
返回兩個(gè)或多個(gè)數(shù)字的平均值。
實(shí)現(xiàn)思路
實(shí)現(xiàn)思路如下:
使用sum函數(shù)求和,然后除以長度count即可,參數(shù)可以使用展開運(yùn)算符來組成一個(gè)數(shù)組,注意需要寫一個(gè)三元表達(dá)式,判斷長度是否為0。
代碼實(shí)現(xiàn)
下面我們來看php和js以及ts代碼的實(shí)現(xiàn):
php代碼實(shí)現(xiàn)
function average(...$arr){
$len = count($arr);
return $len === 0 ? 0 : array_sum($arr) / $len;
}使用示例
average(1, 2, 3); // 2
js代碼實(shí)現(xiàn)
const average = (...arr) => {
const len = arr.length;
return len === 0 ? 0 : arr.reduce((r,i) => r += i,0) / len;
}ts代碼實(shí)現(xiàn)
const average = (...arr: number[]):number => {
const len = arr.length;
return len === 0 ? 0 : arr.reduce((r,i) => r += i,0) / len;
}使用示例
average(1, 2, 3); // 2
總結(jié)
與js/ts實(shí)現(xiàn)不同點(diǎn)如下:
- php可以直接使用
array_sum方法求數(shù)字?jǐn)?shù)組的和,js/ts需要循環(huán)自己計(jì)算(或者自己實(shí)現(xiàn)一個(gè)sum方法)。
數(shù)值限定
將數(shù)值限制在邊界值 a 和 b 指定的包含范圍內(nèi)。
實(shí)現(xiàn)思路
實(shí)現(xiàn)思路如下:
如果該數(shù)值在范圍內(nèi),則返回該數(shù)值,否則,使用最小值方法和最大值方法返回范圍內(nèi)最接近的數(shù)字。
代碼實(shí)現(xiàn)
下面我們來看php和js以及ts代碼的實(shí)現(xiàn):
php代碼實(shí)現(xiàn)
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
js代碼實(shí)現(xiàn)
const clampNumber = (num,a,b) => {
const max = Math.max,min = Math.min;
return max(min(num,max(a,b)),min(a,b));
}ts代碼實(shí)現(xiàn)
const clampNumber = (num:number,a:number,b:number) => {
const max = Math.max,min = Math.min;
return max(min(num,max(a,b)),min(a,b));
}使用示例
clampNumber(2, 3, 5); // 3 clampNumber(1, -1, -5); // -1
總結(jié)
與js/ts實(shí)現(xiàn)不同點(diǎn)如下:
- php的獲取最小值和最大值的方法名叫
min和max,而js/ts則是從Math對象中獲取,即Math.min和Math.max。
組合函數(shù)
返回一個(gè)將多個(gè)函數(shù)組合成單個(gè)可調(diào)用函數(shù)的新函數(shù)。
實(shí)現(xiàn)思路
實(shí)現(xiàn)思路如下:
使用 array_reduce() 執(zhí)行從右到左的函數(shù)組合。該函數(shù)接收3個(gè)參數(shù),第一個(gè)參數(shù)為函數(shù)列表,第二個(gè)參數(shù)是一個(gè)回調(diào)函數(shù)用來合并數(shù)組中的每一個(gè)函數(shù),第三個(gè)參數(shù)是函數(shù)的初始值,即$function($x){ return $x; },默認(rèn)是一個(gè)恒等函數(shù),也就是一個(gè)返回其輸入?yún)?shù)本身的函數(shù)。
代碼實(shí)現(xiàn)
下面我們來看php和js以及ts代碼的實(shí)現(xiàn):
php代碼實(shí)現(xiàn)
function compose(...$fns){
return array_reduce(
$fns,
function ($carry,$fn){
// 使用 use語句導(dǎo)入閉包中的變量$carry,$fn
return function($x) use ($carry,$fn){
return $carry($fn($x));
}
},
$function($x){
return $x;
}
)
}使用示例
$compose = compose(
// 加2
function ($x) {
return $x + 2;
},
// 乘以4
function ($x) {
return $x * 4;
}
);
$compose(3); // 20js代碼實(shí)現(xiàn)
const compose = (...fns) => fns.reduce((f,h) => (...args) => f(h(...args)));
ts代碼實(shí)現(xiàn)
type ComposeFn<T extends any> = (...args: T[]) => T;
const compose = <T,U extends ComposeFn<T>[]>(...fns: U) =>
fns.reduce(
(f, h) =>
(...args: Parameters<ComposeFn<T>>) => f(h(...args))
);
使用示例
const add5 = x => x + 5; const multiply = (x, y) => x * y; const multiplyAndAdd5 = compose(add5, multiply); const res = multiplyAndAdd5(5, 2); // 15
總結(jié)
與js/ts實(shí)現(xiàn)不同點(diǎn)如下:
- php需要使用
use語句來導(dǎo)入閉包中的變量,而js/ts則不需要。 - php使用
array_reduce方法來遍歷函數(shù)數(shù)組,并且需要提供一個(gè)恒等函數(shù)作為第三個(gè)參數(shù)的初始值,而js/ts直接調(diào)用數(shù)組的reduce方法來遍歷函數(shù)數(shù)組,并且不需要提供第三個(gè)作為初始值的參數(shù)。
統(tǒng)計(jì)字符串中元音字母的數(shù)量
返回所提供字符串中的元音字母數(shù)量。
實(shí)現(xiàn)思路
實(shí)現(xiàn)思路如下:
使用正則表達(dá)式來匹配元音字母,元音字母包含a、e、i、o、u等字母。調(diào)用php的preg_match_all方法來匹配,然后使用count方法計(jì)算返回值的長度,即為元音字母的數(shù)量。
代碼實(shí)現(xiàn)
下面我們來看php和js以及ts代碼的實(shí)現(xiàn):
php代碼實(shí)現(xiàn)
function countVowels($str){
preg_match_all('/[aeiou]/i',$str,$matches);
// $matches為匹配結(jié)果
return count($matches[0]);
}使用示例
countVowels('sampleInput'); // 4js代碼實(shí)現(xiàn)
const countVowels = (str) => [...str.matchAll(/[aeiou]/ig)].length;
ts代碼實(shí)現(xiàn)
const countVowels = (str: string) => [...str.matchAll(/[aeiou]/ig)].length;
使用示例
countVowels('sampleInput'); // 4總結(jié)
與js/ts實(shí)現(xiàn)不同點(diǎn)如下:
- php使用
preg_match_all方法來匹配字符串所有符合條件的字符,而js/ts則使用String.matchAll方法。 - php 定義正則表達(dá)式和js/ts有所區(qū)別,需要把正則表達(dá)式當(dāng)作一個(gè)字符串。
- js/ts調(diào)用
matchAll方法時(shí)需要提供一個(gè)g修飾符,表示用來匹配全局,php則不需要。 - js/ts調(diào)用
matchAll方法返回的是一個(gè)迭代器,需要使用展開運(yùn)算符轉(zhuǎn)換成數(shù)組,然后再計(jì)算長度。 - php使用
count方法來獲取數(shù)組的長度,而js/ts可以直接通過length屬性來獲取。
柯里化函數(shù)
對函數(shù)進(jìn)行柯里化,以便在多次調(diào)用中獲取參數(shù)。
實(shí)現(xiàn)思路
實(shí)現(xiàn)思路如下:
curry接收一個(gè)函數(shù)參數(shù),返回執(zhí)行的累積器$acc。- 使用
&操作符引用累積器,使用use語句導(dǎo)入函數(shù)和累積器。 - 使用
array_merge方法合并所有參數(shù)。 - 使用php反射
ReflectionFunction獲取函數(shù)所需參數(shù)數(shù)量,然后調(diào)用getNumberOfRequiredParameters方法獲取必需參數(shù)的數(shù)量。 - 如果必需參數(shù)數(shù)量小于等于外部參數(shù)數(shù)量,則直接返回函數(shù)執(zhí)行參數(shù)結(jié)果,否則遞歸的執(zhí)行累積器。
代碼實(shí)現(xiàn)
下面我們來看php和js以及ts代碼的實(shí)現(xiàn):
php代碼實(shí)現(xiàn)
function curry($fn){
$acc = function ($arg) use ($fn,&$acc){
return function (...$args) use($fn,$arg,$acc){
// 合并參數(shù)
$arg = array_merge($args);
// 創(chuàng)建一個(gè)反射
$ref = new ReflectionFunction($fn);
// 通過反射獲取必需參數(shù)
$totalArgs = $ref -> getNumberOfRequiredParameters();
if($totalArgs <= count($arg)){
return $fn(...$arg);
}
return $acc($arg);
}
}
return $acc([]);
}使用示例
$curriedAdd = curry(function ($a, $b) { return $a + $b; });
$add10 = $curriedAdd(10);
var_dump($add10(15)); // 25js代碼實(shí)現(xiàn)
const curry = fn => (...args) => args.length >= fn.length ? fn(...args) : (...nArgs) => curry(fn)(...args,...nArgs);
ts代碼實(shí)現(xiàn)
const curry =
<T, R, F extends (...args: T[]) => R>(fn: F) =>
(...args: T[]) =>
args.length >= fn.length
? fn(...args)
: (...nArgs: T[]) => curry(fn as (...args: unknown[]) => unknown)(...args, ...nArgs);使用示例
const curriedAdd = curry((a,b) => a + b); const add10 = curriedAdd(10); const res = add10(15); // 25
總結(jié)
與js/ts實(shí)現(xiàn)不同點(diǎn)如下:
- php中使用了反射相關(guān)方法來獲取參數(shù),而js/ts則不需要。
- php使用
array_merge方法來合并參數(shù),而js/ts則不需要。 - 兩者的判斷邏輯也有差異。
ps: 兩者的實(shí)現(xiàn)都采用了遞歸的方式,這點(diǎn)需要注意。
取消字符串首字母大寫
取消字符串首字母的大寫。
實(shí)現(xiàn)思路
實(shí)現(xiàn)思路如下:
調(diào)用lcfirst方法可以直接將字符串大寫首字母轉(zhuǎn)換成小寫,根據(jù)第二個(gè)參數(shù)$upperRest來決定是否將其余字母轉(zhuǎn)換成大寫,使用strtoupper方法即可。
代碼實(shí)現(xiàn)
下面我們來看php和js以及ts代碼的實(shí)現(xiàn):
php代碼實(shí)現(xiàn)
function decapitalize($str,$upperRest = false){
return lcfirst($upperRest ? strtoupper($str) : $str);
}使用示例
decapitalize('FooBar'); // 'fooBar'js代碼實(shí)現(xiàn)
const decapitalize = (str, upperRest = false) => str.slice(0,1).toLowerCase() + `${upperRest ? str.slice(1).toUpperCase() : str.slice(1)}`;ts代碼實(shí)現(xiàn)
const decapitalize = (str: string, upperRest = false) => str.slice(0,1).toLowerCase() + `${upperRest ? str.slice(1).toUpperCase() : str.slice(1)}`;使用示例
decapitalize('FooBar'); // 'fooBar'總結(jié)
與js/ts實(shí)現(xiàn)不同點(diǎn)如下:
- php有方法可以直接將首字母轉(zhuǎn)換成小寫,而js/ts則需要通過
slice(或其它字符串的截取方法,例如:substr)方法來截取字符串,然后拼接在一起。 - php轉(zhuǎn)換成大寫的方法是
strtoupper,而js/ts則是通過調(diào)用String.toUpperCase方法來轉(zhuǎn)換成大寫。
深度展開數(shù)組
深度展平數(shù)組,直接將多維數(shù)組轉(zhuǎn)成一維數(shù)組。
實(shí)現(xiàn)思路
實(shí)現(xiàn)思路如下:
使用foreach循環(huán)數(shù)組,如果數(shù)組項(xiàng)是數(shù)組(使用is_array方法來判斷),則使用遞歸加array_push和空數(shù)組以及展開運(yùn)算符來合并數(shù)組,否則直接使用[]語法來添加數(shù)組項(xiàng)(相當(dāng)于array_push方法)。
代碼實(shí)現(xiàn)
下面我們來看php和js以及ts代碼的實(shí)現(xiàn):
php代碼實(shí)現(xiàn)
function deepFlatten($items){
$res = [];
foreach($item as $items){
if(is_array($item)){
array_push($res,...deepFlatten($item));
}else{
$res[] = $item;
}
}
return $res;
}使用示例
deepFlatten([1, [2], [[3], 4], 5]); // [1, 2, 3, 4, 5]
js代碼實(shí)現(xiàn)
const deepFlatten = (items) => {
let res = [];
for(const item of items){
if(Array.isArray(item) && item.length > 0){
res.push(...deepFlatten(item))
}else{
res.push(item)
}
}
return res;
}ts代碼實(shí)現(xiàn)
const deepFlatten = <T>(items: T[]) => {
let res: T[] = [];
for (const item of items) {
if (Array.isArray(item) && item.length > 0) {
res.push(...deepFlatten(item));
} else {
res.push(item);
}
}
return res;
};使用示例
deepFlatten([1, [2], [[3], 4], 5]); // [1, 2, 3, 4, 5]
總結(jié)
與js/ts實(shí)現(xiàn)不同點(diǎn)如下:
- php使用
array_push方法來往數(shù)組末尾添加元素,而js/ts則是直接使用push方法。 - php可以使用
[]語法來代替array_push方法,js/ts沒有相關(guān)語法。 - php使用
is_array方法來判斷是否是數(shù)組,而js/ts則使用Array.isArray方法。 - php使用
foreach循環(huán)遍歷數(shù)組,js/ts沒有foreach循環(huán),但可以使用for循環(huán)代替。
到此這篇關(guān)于一些實(shí)用的PHP函數(shù)(對比js/ts實(shí)現(xiàn),附代碼)的文章就介紹到這了,更多相關(guān)實(shí)用的PHP函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
判斷php數(shù)組是否為索引數(shù)組的實(shí)現(xiàn)方法
本篇文章是對判斷php數(shù)組是否為索引數(shù)組的方法進(jìn)行了詳細(xì)的分析介紹,需要的朋友參考下2013-06-06
Zend Studio 實(shí)用快捷鍵一覽表(精心整理)
以下是小編精心整理的Zend Studio實(shí)用快捷鍵。很有用哦!需要的朋友可以過來參考下2013-08-08
PHP函數(shù)rtrim()使用中的怪異現(xiàn)象分析
這篇文章主要介紹了PHP函數(shù)rtrim()使用中的怪異現(xiàn)象,結(jié)合具體實(shí)例形式分析了php函數(shù)rtrim在進(jìn)行字符匹配過程中出現(xiàn)的問題與解決方法,有助于進(jìn)一步了解rtrim函數(shù)的原理與使用技巧,需要的朋友可以參考下2017-02-02
PHP Global變量定義當(dāng)前頁面的全局變量實(shí)現(xiàn)探討
我們在這篇文章中就針對PHP Global變量出現(xiàn)的問題給出了一些具體的解決辦法,感興趣的朋友可以參考下哈2013-06-06
PHP使用微信開發(fā)模式實(shí)現(xiàn)搜索已發(fā)送圖文及匹配關(guān)鍵字回復(fù)的方法
這篇文章主要介紹了PHP使用微信開發(fā)模式實(shí)現(xiàn)搜索已發(fā)送圖文及匹配關(guān)鍵字回復(fù)的方法,涉及php針對微信json格式數(shù)據(jù)的解析與正則匹配相關(guān)操作技巧,需要的朋友可以參考下2017-09-09
PHP提示Cannot modify header information - headers already sent
這篇文章主要介紹了PHP提示Cannot modify header information - headers already sent by解決方法,是在PHP程序開發(fā)中非常典型的錯誤情況,非常具有實(shí)用價(jià)值,需要的朋友可以參考下2014-09-09
php 處理上百萬條的數(shù)據(jù)庫如何提高處理查詢速度
php 處理上百萬條的數(shù)據(jù)庫如何提高處理查詢速度2010-02-02
php壓縮多個(gè)CSS為一個(gè)css的代碼并緩存
壓縮多個(gè)CSS文件成一個(gè)并緩存一個(gè)小時(shí)。也可以使用相同的JavaScript代碼,但替換下面的“文本/的CSS“和”文本 JavaScript的“,當(dāng)然一定要包括。代替的。css的js文件。2011-04-04

