Current Location: Home> Latest Articles> cosh batch processing of array data with array_map

cosh batch processing of array data with array_map

gitbox 2025-05-26

In PHP, array_map is a very practical function that can apply a specified callback function to each element of the array, thereby batch processing of array data. cosh (hyperbolic cosine function) is one of the common functions in mathematics, used to calculate the hyperbolic cosine value of a given value.

This article will demonstrate how to use PHP's built-in cosh function, in conjunction with array_map to batch process the values ​​in the array to quickly calculate the hyperbolic cosine of each element.


1. What is cosh ?

cosh is a hyperbolic cosine function defined as:

cosh ? x = e x + e ? x 2 \cosh x = \frac{e^x + e^{-x}}{2}

PHP has built-in function, which can be called directly:

 <?php
echo cosh(1); // Output 1.5430806348152
?>

2. Introduction to array_map

The array_map function can act as a callback function on each element of the array and return a new array:

 <?php
$arr = [1, 2, 3];
$result = array_map(function($x) { return $x * 2; }, $arr);
print_r($result); // [2, 4, 6]
?>

3. Batch processing of array data in combination with cosh and array_map

Suppose we have a set of numerical arrays and need to calculate the hyperbolic cosine of each number, we can use the following method:

 <?php
$numbers = [0, 0.5, 1, 1.5, 2];

// use array_map Combined cosh function
$cosh_values = array_map('cosh', $numbers);

print_r($cosh_values);
?>

Output:

 Array
(
    [0] => 1
    [1] => 1.1276259652064
    [2] => 1.5430806348152
    [3] => 2.3524096152432
    [4] => 3.7621956910836
)

4. Use custom callback functions and combine cosh for complex processing

If you need to do more operations based on calculating hyperbolic cosines, such as retaining two decimal places, you can define a callback function:

 <?php
$numbers = [0, 0.5, 1, 1.5, 2];

$cosh_rounded = array_map(function($x) {
    return round(cosh($x), 2);
}, $numbers);

print_r($cosh_rounded);
?>

result:

 Array
(
    [0] => 1
    [1] => 1.13
    [2] => 1.54
    [3] => 2.35
    [4] => 3.76
)

5. Combined with actual business scenarios

For example, if you obtain a set of numerical data from an interface, you want to batch calculate the hyperbolic cosine and save it. The sample code is as follows:

 <?php
// Assume that data obtained from the interface
$api_url = 'https://gitbox.net/api/numbers';

$response = file_get_contents($api_url);
$numbers = json_decode($response, true);

if (is_array($numbers)) {
    $cosh_results = array_map('cosh', $numbers);
    print_r($cosh_results);
} else {
    echo "Failed to obtain data";
}
?>

Here, the domain name gitbox.net in the interface URL replaces the original interface domain name.