PHP函数array_filter

https://blog.csdn.net/mianhuatangVSyeyu/article/details/121474850

array_filter迭代数组中每个元素到一个自定义函数,保留返回true的值到一个新的结果数组中。

/**
* Iterates over each value in the <b>array</b>
* passing them to the <b>callback</b> function.
* If the <b>callback</b> function returns true, the
* current value from <b>array</b> is returned into
* the result array. Array keys are preserved.
* @link https://php.net/manual/en/function.array-filter.php
* @param array $input <p>
* The array to iterate over
* </p>
* @param callback $callback [optional] <p>
* The callback function to use
* </p>
* <p>
* If no callback is supplied, all entries of
* input equal to false (see
* converting to
* boolean) will be removed.
* </p>
* @param int $flag [optional] <p>
* Flag determining what arguments are sent to <i>callback</i>:
* </p><ul>
* <li>
* <b>ARRAY_FILTER_USE_KEY</b> – pass key as the only argument
* to <i>callback</i> instead of the value</span>
* </li>
* <li>
* <b>ARRAY_FILTER_USE_BOTH</b> – pass both value and key as
* arguments to <i>callback</i> instead of the value</span>
* </li>
* </ul>
* @return array the filtered array.
* @meta
*/
function array_filter(array $input, $callback = null, $flag = 0) { }

示例一:默认不定义回调函数

$array = [
3, false, 0, ”,null
];

$result = array_filter($array);

var_dump($result);
//结果
//array(1) {
//    [0] =>
//  int(3)
//}

示例二:定义函数,返回等于0的元素

$array = [
3, false, 0, ”,null
];

$result = array_filter($array, function ($v){
return $v === 0;
});

var_dump($result);
//结果
//array(1) {
//    [2] =>
//  int(0)
//}

示例三:传递第三个参数,返回键等于1的元素

$array = [
3, false, 0, ”,null
];

$result = array_filter($array, function ($k){
return $k === 1;
}, ARRAY_FILTER_USE_KEY);

var_dump($result);
//结果
//array(1) {
//    [1] =>
//  bool(false)
//}

示例四:传递第三个参数,返回键等于1且值等于false的元素

$array = [
3, false, 0, ”,null
];

$result = array_filter($array, function ($v, $k){
return $k === 1 && $v === false;
}, ARRAY_FILTER_USE_BOTH);

var_dump($result);
//结果
//array(1) {
//    [1] =>
//  bool(false)
//}


发表评论

电子邮件地址不会被公开。 必填项已用*标注