分享一些實用的PHP函數(shù)(對比js/ts實現(xiàn),附代碼)
檢查數(shù)組所有元素是否滿足給定條件
如果提供的函數(shù)對數(shù)組的所有元素返回 true,則返回 true,否則返回 false。
思路
實現(xiàn)思路如下:
使用數(shù)組的filter方法對數(shù)組執(zhí)行給定的函數(shù),然后使用count方法獲取執(zhí)行后的結(jié)果,再和count方法獲取未執(zhí)行filter方法的結(jié)果進行比較。
代碼實現(xiàn)
下面我們來看php和js以及ts代碼的實現(xiàn):
php代碼實現(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代碼實現(xiàn)
const all = (arr,fn) => arr.filter(fn).length === arr.length;
ts代碼實現(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實現(xiàn)不同點如下:
- php通過
count方法來獲取數(shù)組的長度,而js/ts則可以直接通過length來獲取數(shù)組的長度。 - php的
filter方法名叫array_filter,而js/ts則是叫filter。
檢查數(shù)組所有元素是否有一項滿足給定條件
如果提供的函數(shù)對數(shù)組的至少一個元素返回 true,則返回 true,否則返回 false。
實現(xiàn)思路
實現(xiàn)思路和前面的all函數(shù)很相似,只不過這里不需要做比較,只需要判斷長度大于0即可。
代碼實現(xiàn)
下面我們來看php和js以及ts代碼的實現(xiàn):
php代碼實現(xiàn)
function any($arr,$fn){
return count(array_filter($arr,$fn)) > 0;
}使用示例
any([2, 3, 4, 5], function ($item) {
return $item < 3;
}); // truejs代碼實現(xiàn)
const any = (arr,fn) => arr.filter(fn).length > 0;
ts代碼實現(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 個數(shù)字是否大致相等
檢查兩個數(shù)字是否大致相等。
實現(xiàn)思路
實現(xiàn)思路如下:
該函數(shù)有3個參數(shù),通過abs方法計算前面2個參數(shù)的絕對差值,然后與第三個參數(shù)進行比較,判斷是否小于第三個參數(shù),第三個參數(shù)默認值是0.001。
代碼實現(xiàn)
下面我們來看php和js以及ts代碼的實現(xiàn):
php代碼實現(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代碼實現(xiàn)
const apprEqual = (a,b,c = 0.001) => Math.abs(a - b) < c;
ts代碼實現(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實現(xiàn)不同點如下:
- php的獲取絕對值的方法名叫
abs,而js/ts則是從Math對象中獲取,即Math.abs。
平均值
返回兩個或多個數(shù)字的平均值。
實現(xiàn)思路
實現(xiàn)思路如下:
使用sum函數(shù)求和,然后除以長度count即可,參數(shù)可以使用展開運算符來組成一個數(shù)組,注意需要寫一個三元表達式,判斷長度是否為0。
代碼實現(xiàn)
下面我們來看php和js以及ts代碼的實現(xiàn):
php代碼實現(xiàn)
function average(...$arr){
$len = count($arr);
return $len === 0 ? 0 : array_sum($arr) / $len;
}使用示例
average(1, 2, 3); // 2
js代碼實現(xiàn)
const average = (...arr) => {
const len = arr.length;
return len === 0 ? 0 : arr.reduce((r,i) => r += i,0) / len;
}ts代碼實現(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實現(xiàn)不同點如下:
- php可以直接使用
array_sum方法求數(shù)字數(shù)組的和,js/ts需要循環(huán)自己計算(或者自己實現(xiàn)一個sum方法)。
數(shù)值限定
將數(shù)值限制在邊界值 a 和 b 指定的包含范圍內(nèi)。
實現(xiàn)思路
實現(xiàn)思路如下:
如果該數(shù)值在范圍內(nèi),則返回該數(shù)值,否則,使用最小值方法和最大值方法返回范圍內(nèi)最接近的數(shù)字。
代碼實現(xiàn)
下面我們來看php和js以及ts代碼的實現(xiàn):
php代碼實現(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代碼實現(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代碼實現(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實現(xiàn)不同點如下:
- php的獲取最小值和最大值的方法名叫
min和max,而js/ts則是從Math對象中獲取,即Math.min和Math.max。
組合函數(shù)
返回一個將多個函數(shù)組合成單個可調(diào)用函數(shù)的新函數(shù)。
實現(xiàn)思路
實現(xiàn)思路如下:
使用 array_reduce() 執(zhí)行從右到左的函數(shù)組合。該函數(shù)接收3個參數(shù),第一個參數(shù)為函數(shù)列表,第二個參數(shù)是一個回調(diào)函數(shù)用來合并數(shù)組中的每一個函數(shù),第三個參數(shù)是函數(shù)的初始值,即$function($x){ return $x; },默認是一個恒等函數(shù),也就是一個返回其輸入?yún)?shù)本身的函數(shù)。
代碼實現(xiàn)
下面我們來看php和js以及ts代碼的實現(xiàn):
php代碼實現(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代碼實現(xiàn)
const compose = (...fns) => fns.reduce((f,h) => (...args) => f(h(...args)));
ts代碼實現(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實現(xiàn)不同點如下:
- php需要使用
use語句來導(dǎo)入閉包中的變量,而js/ts則不需要。 - php使用
array_reduce方法來遍歷函數(shù)數(shù)組,并且需要提供一個恒等函數(shù)作為第三個參數(shù)的初始值,而js/ts直接調(diào)用數(shù)組的reduce方法來遍歷函數(shù)數(shù)組,并且不需要提供第三個作為初始值的參數(shù)。
統(tǒng)計字符串中元音字母的數(shù)量
返回所提供字符串中的元音字母數(shù)量。
實現(xiàn)思路
實現(xiàn)思路如下:
使用正則表達式來匹配元音字母,元音字母包含a、e、i、o、u等字母。調(diào)用php的preg_match_all方法來匹配,然后使用count方法計算返回值的長度,即為元音字母的數(shù)量。
代碼實現(xiàn)
下面我們來看php和js以及ts代碼的實現(xiàn):
php代碼實現(xiàn)
function countVowels($str){
preg_match_all('/[aeiou]/i',$str,$matches);
// $matches為匹配結(jié)果
return count($matches[0]);
}使用示例
countVowels('sampleInput'); // 4js代碼實現(xiàn)
const countVowels = (str) => [...str.matchAll(/[aeiou]/ig)].length;
ts代碼實現(xiàn)
const countVowels = (str: string) => [...str.matchAll(/[aeiou]/ig)].length;
使用示例
countVowels('sampleInput'); // 4總結(jié)
與js/ts實現(xiàn)不同點如下:
- php使用
preg_match_all方法來匹配字符串所有符合條件的字符,而js/ts則使用String.matchAll方法。 - php 定義正則表達式和js/ts有所區(qū)別,需要把正則表達式當(dāng)作一個字符串。
- js/ts調(diào)用
matchAll方法時需要提供一個g修飾符,表示用來匹配全局,php則不需要。 - js/ts調(diào)用
matchAll方法返回的是一個迭代器,需要使用展開運算符轉(zhuǎn)換成數(shù)組,然后再計算長度。 - php使用
count方法來獲取數(shù)組的長度,而js/ts可以直接通過length屬性來獲取。
柯里化函數(shù)
對函數(shù)進行柯里化,以便在多次調(diào)用中獲取參數(shù)。
實現(xiàn)思路
實現(xiàn)思路如下:
curry接收一個函數(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í)行累積器。
代碼實現(xiàn)
下面我們來看php和js以及ts代碼的實現(xiàn):
php代碼實現(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)建一個反射
$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代碼實現(xiàn)
const curry = fn => (...args) => args.length >= fn.length ? fn(...args) : (...nArgs) => curry(fn)(...args,...nArgs);
ts代碼實現(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實現(xiàn)不同點如下:
- php中使用了反射相關(guān)方法來獲取參數(shù),而js/ts則不需要。
- php使用
array_merge方法來合并參數(shù),而js/ts則不需要。 - 兩者的判斷邏輯也有差異。
ps: 兩者的實現(xiàn)都采用了遞歸的方式,這點需要注意。
取消字符串首字母大寫
取消字符串首字母的大寫。
實現(xiàn)思路
實現(xiàn)思路如下:
調(diào)用lcfirst方法可以直接將字符串大寫首字母轉(zhuǎn)換成小寫,根據(jù)第二個參數(shù)$upperRest來決定是否將其余字母轉(zhuǎn)換成大寫,使用strtoupper方法即可。
代碼實現(xiàn)
下面我們來看php和js以及ts代碼的實現(xiàn):
php代碼實現(xiàn)
function decapitalize($str,$upperRest = false){
return lcfirst($upperRest ? strtoupper($str) : $str);
}使用示例
decapitalize('FooBar'); // 'fooBar'js代碼實現(xiàn)
const decapitalize = (str, upperRest = false) => str.slice(0,1).toLowerCase() + `${upperRest ? str.slice(1).toUpperCase() : str.slice(1)}`;ts代碼實現(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實現(xià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ù)組。
實現(xiàn)思路
實現(xiàn)思路如下:
使用foreach循環(huán)數(shù)組,如果數(shù)組項是數(shù)組(使用is_array方法來判斷),則使用遞歸加array_push和空數(shù)組以及展開運算符來合并數(shù)組,否則直接使用[]語法來添加數(shù)組項(相當(dāng)于array_push方法)。
代碼實現(xiàn)
下面我們來看php和js以及ts代碼的實現(xiàn):
php代碼實現(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代碼實現(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代碼實現(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實現(xià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)于一些實用的PHP函數(shù)(對比js/ts實現(xiàn),附代碼)的文章就介紹到這了,更多相關(guān)實用的PHP函數(shù)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Sphinx創(chuàng)建全文檢索的索引介紹
本篇文章是對使用Sphinx創(chuàng)建全文檢索的索引進行了詳細的分析介紹,需要的朋友參考下2013-06-06
PHP小技巧之JS和CSS優(yōu)化工具Minify的使用方法
為減少HTTP請求,我們往往需要合并和壓縮多個JS和CSS文件,下面記錄下網(wǎng)上關(guān)于實現(xiàn)這個功能的PHP源碼以及開源項目Minify的使用方法2014-05-05
通過JavaScript或PHP檢測Android設(shè)備的代碼
在此列出一些能夠在iOS的最大競爭者——安卓(Android)系統(tǒng)的檢測方法。即通過JavaScript或PHP檢測Android設(shè)備,給大家提供參考。2011-03-03
PHP中empty,isset,is_null用法和區(qū)別
最近在閱讀項目的源碼,發(fā)現(xiàn)源碼中就對empty、isset和is_null函數(shù)(語言特性)亂用,有的地方很明顯的就挖坑了。不能正確的去理解這些東西,就很可能給后續(xù)的開發(fā)挖坑了。2017-02-02
PHP實現(xiàn)簡單的協(xié)程任務(wù)調(diào)度demo示例
這篇文章主要介紹了PHP實現(xiàn)簡單的協(xié)程任務(wù)調(diào)度demo,結(jié)合實例形式詳細分析了PHP基于協(xié)程的任務(wù)調(diào)度基本原理、定義及使用技巧,需要的朋友可以參考下2020-02-02
PHP數(shù)據(jù)庫操作之基于Mysqli的數(shù)據(jù)庫操作類庫
Mysqli 是什么,我這里也不進行描述了。因為網(wǎng)上關(guān)于 Mysqli 的教程數(shù)不勝數(shù),我這里為大家介紹一款基于 Mysqli 的操作數(shù)據(jù)庫類(M.class.php)2014-04-04
PHP實現(xiàn)根據(jù)瀏覽器跳轉(zhuǎn)不同語言頁面代碼
以下是對使用PHP實現(xiàn)根據(jù)瀏覽器跳轉(zhuǎn)不同語言頁面的代碼進行了介紹,需要的朋友可以過來參考下2013-08-08

