Home> php教程> php手册> body text

PHP将回调函数作用到给定数组单元的方法

WBOY
Release: 2016-06-06 20:19:24
Original
969 people have browsed it

这篇文章主要介绍了PHP将回调函数作用到给定数组单元的方法,是十分重要的一种应用,需要的朋友可以参考下

数组是PHP程序设计中十分重要的一环。本文介绍PHP中数组函数array_map()的用法,实现将回调函数作用到给定数组单元上。具体如下:

array array_map ( callable $callback , array $arr1 [, array $... ] )

array_map() 返回一个数组,,该数组包含了 arr1 中的所有单元经过 callback 作用过之后的单元。

callback 接受的参数数目应该和传递给 array_map() 函数的数组数目一致。

示例程序如下:

function fun($n) { return $n * $n * $n; } $a = array(1, 2, 3, 4, 5); $b = array_map('fun', $a); /* 每个数组单元作三次方运算,返回数组 */ print_r($b);

输出结果为:

Array ( [0] => 1 [1] => 8 [2] => 27 [3] => 64 [4] => 125 )

此外,array_map()函数还有如下几种用法:

array_map('unlink', glob('*.txt'));/* glob返回"文件名.txt"组成的数组,然后对每个文件进行删除操作*/ array_map('unlink', glob('*.*')); array_map('unlink', glob('*'));

如果不使用array_map(),对数组每个单元进行操作就只能遍历然后适当组装。

更多的应用读者可以根据具体的项目需求进行挖掘。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
    Latest Downloads
    More>
    Web Effects
    Website Source Code
    Website Materials
    Front End Template
    About us Disclaimer Sitemap
    php.cn:Public welfare online PHP training,Help PHP learners grow quickly!