欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

分享一些實用的PHP函數(shù)(對比js/ts實現(xiàn),附代碼)

 更新時間:2025年08月11日 10:42:30   作者:胖頭魚不吃魚-  
PHP是一種功能強大、易學(xué)易用的Web編程語言,適用于各種規(guī)模的Web項目,這篇文章主要介紹了一些實用的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;
}); // true

js代碼實現(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)不同點如下:

  1. php通過count方法來獲取數(shù)組的長度,而js/ts則可以直接通過length來獲取數(shù)組的長度。
  2. 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;
}); // true

js代碼實現(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)不同點如下:

  1. 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)不同點如下:

  1. 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)不同點如下:

  1. php的獲取最小值和最大值的方法名叫minmax,而js/ts則是從Math對象中獲取,即Math.minMath.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); // 20

js代碼實現(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)不同點如下:

  1. php需要使用use語句來導(dǎo)入閉包中的變量,而js/ts則不需要。
  2. 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'); // 4

js代碼實現(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)不同點如下:

  1. php使用preg_match_all方法來匹配字符串所有符合條件的字符,而js/ts則使用String.matchAll方法。
  2. php 定義正則表達式和js/ts有所區(qū)別,需要把正則表達式當(dāng)作一個字符串。
  3. js/ts調(diào)用matchAll方法時需要提供一個g修飾符,表示用來匹配全局,php則不需要。
  4. js/ts調(diào)用matchAll方法返回的是一個迭代器,需要使用展開運算符轉(zhuǎn)換成數(shù)組,然后再計算長度。
  5. php使用count方法來獲取數(shù)組的長度,而js/ts可以直接通過length屬性來獲取。

柯里化函數(shù)

對函數(shù)進行柯里化,以便在多次調(diào)用中獲取參數(shù)。

實現(xiàn)思路

實現(xiàn)思路如下:

  1. curry接收一個函數(shù)參數(shù),返回執(zhí)行的累積器$acc。
  2. 使用&操作符引用累積器,使用use語句導(dǎo)入函數(shù)和累積器。
  3. 使用array_merge方法合并所有參數(shù)。
  4. 使用php反射ReflectionFunction獲取函數(shù)所需參數(shù)數(shù)量,然后調(diào)用getNumberOfRequiredParameters方法獲取必需參數(shù)的數(shù)量。
  5. 如果必需參數(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)); // 25

js代碼實現(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)不同點如下:

  1. php中使用了反射相關(guān)方法來獲取參數(shù),而js/ts則不需要。
  2. php使用array_merge方法來合并參數(shù),而js/ts則不需要。
  3. 兩者的判斷邏輯也有差異。

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)不同點如下:

  1. php有方法可以直接將首字母轉(zhuǎn)換成小寫,而js/ts則需要通過slice(或其它字符串的截取方法,例如:substr)方法來截取字符串,然后拼接在一起。
  2. 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)不同點如下:

  1. php使用array_push方法來往數(shù)組末尾添加元素,而js/ts則是直接使用push方法。
  2. php可以使用[]語法來代替array_push方法,js/ts沒有相關(guān)語法。
  3. php使用is_array方法來判斷是否是數(shù)組,而js/ts則使用Array.isArray方法。
  4. 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)文章

最新評論