⊗ppSpFnIFC 12 of 95 menu

Callbacks in Built-in Functions in PHP

PHP has a number of built-in functions that accept callbacks as a parameter. We will study the general principle of working with them using the array_map function as an example. This function accepts a callback as the first parameter, and an array as the second. The function applies the callback to each element of the array and returns the modified array.

Let's look at the options for using this function, taking into account the knowledge we have previously acquired.

Option 1

Extract the square root from each element of the array using the built-in function sqrt. To do this, we will pass a string with the name of this function as the callback parameter:

<?php $arr = [1, 2, 3, 4, 5]; $res = array_map('sqrt', $arr); var_dump($res); ?>

Option 2

Square each element of the array using a regular function we created. To do this, we will pass a string with the name of this function as the callback parameter:

<?php $arr = [1, 2, 3, 4, 5]; function func($num) { return $num ** 2; } $res = array_map('func', $arr); var_dump($res); ?>

Option 3

Let's convert our function into an anonymous one, assigned to a variable:

<?php $arr = [1, 2, 3, 4, 5]; $func = function ($num) { return $num ** 2; }; $res = array_map($func, $arr); var_dump($res); ?>

Option 4

Pass the anonymous function directly as a parameter:

<?php $arr = [1, 2, 3, 4, 5]; $res = array_map(function ($num) { return $num ** 2; }, $arr); var_dump($res); ?>

Option 5

Use an arrow function:

<?php $arr = [1, 2, 3, 4, 5]; $res = array_map(fn ($num) => $num ** 2, $arr); var_dump($res); ?>

Option 6

Now let the power to which the number needs to be raised be set by an external variable of the callback. Let's use this variable by accessing it via use:

<?php $arr = [1, 2, 3, 4, 5]; $pow = 3; $res = array_map(function ($num) use ($pow) { return $num ** $pow; }, $arr); var_dump($res); ?>

Option 7

Rewrite the previous code using an arrow function. Now the variable $pow will be available automatically:

<?php $arr = [1, 2, 3, 4, 5]; $pow = 3; $res = array_map(fn ($num) => $num ** $pow, $arr); var_dump($res); ?>

Practical Tasks

Given an array with strings. Convert the text of each element of the array to uppercase.

Given an array with strings. Reverse the text of each element of the array so that the characters go in reverse order.

byenru