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.
cosh is a hyperbolic cosine function defined as:
PHP has built-in function, which can be called directly:
<?php
echo cosh(1); // Output 1.5430806348152
?>
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]
?>
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
)
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
)
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.