PHP A method that applies a callback function to a given array cell

  • 2021-07-13 04:53:36
  • OfStack

Array is an important ring in PHP programming. This paper introduces the use of the array function array_map () in PHP, and implements the callback function on a given array unit. The details are as follows:


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

array_map () returns an array that contains all the cells in arr1 after being treated by callback.

The number of arguments callback accepts should be equal to the number of arrays passed to the array_map () function.

The sample program is as follows:


function fun($n)
{
 return $n * $n * $n;
}

$a = array(1, 2, 3, 4, 5);
$b = array_map('fun', $a); /*  Each array unit is made as 3 Power operation, returning array  */
print_r($b);

The output is:


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

In addition, the array_map () function is used in the following ways:


array_map('unlink', glob('*.txt'));/* glob Return " Filename .txt" And then delete each file */

array_map('unlink', glob('*.*'));

array_map('unlink', glob('*'));

If you don't use array_map (), you can only iterate through each cell of the array and assemble it properly.

More application readers can mine according to specific project requirements.


Related articles: