In PHP, the ceil function is used to round a number up to the nearest integer, while the array_map function applies a specified callback to each element in an array. When you need to round up all the values in an array, combining these two functions offers a concise and efficient solution.
The ceil function accepts a floating-point number as a parameter and returns the smallest integer greater than or equal to that number. For example:
echo ceil(3.14); // Outputs 4
echo ceil(-1.7); // Outputs -1
The array_map function applies a given callback function to each element of an array and returns a new array with the applied results.
$arr = [1, 2, 3];
$result = array_map(function($item) {
return $item * 2;
}, $arr);
// $result is [2, 4, 6]
By combining the above two functions, we can write the following code to round up each value in an array:
$numbers = [1.2, 2.5, 3.7, 4.0, 5.9];
$rounded = array_map('ceil', $numbers);
print_r($rounded);
The output will be:
Array
(
[0] => 2
[1] => 3
[2] => 4
[3] => 4
[4] => 6
)
Here, array_map directly passes the function name 'ceil' as the callback, and PHP automatically calls ceil on each element of the array.
If you want to perform additional operations beyond rounding up, you can pass a custom callback function:
$numbers = [1.2, 2.5, 3.7];
$processed = array_map(function($num) {
return ceil($num) * 10;
}, $numbers);
print_r($processed);
Result:
Array
(
[0] => 20
[1] => 30
[2] => 40
)
Uniformly rounding up a list of floating-point numbers entered by users for easier subsequent calculations or display.
Standardizing numerical data in data analysis.
<?php
// Initialize an array of floating-point numbers
$floatValues = [0.1, 1.6, 2.3, 3.9, 4.4];
<p>// Use array_map and ceil to round up the array elements<br>
$ceilValues = array_map('ceil', $floatValues);</p>
<p>// Output the result<br>
echo "<pre>";<br>
print_r($ceilValues);<br>
echo "
";Related Tags:
array_map