search
Homephp教程php手册PHP将回调函数作用到给定数组单元的方法

这篇文章主要介绍了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(),对数组每个单元进行操作就只能遍历然后适当组装。

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

Statement
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools