Current Location: Home> Latest Articles> How to Use the ceil Function with array_map to Round Up Each Value in an Array?

How to Use the ceil Function with array_map to Round Up Each Value in an Array?

gitbox 2025-06-27

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 function to each element in an array. When you need to round up every number in an array, combining these two functions offers a concise and efficient way to achieve this.

1. Introduction to the ceil Function

The ceil function takes a floating-point number as an argument 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

2. Introduction to the array_map Function

The array_map function applies a given callback function to each element of an array and returns a new array with the results.

$arr = [1, 2, 3];
$result = array_map(function($item) {
    return $item * 2;
}, $arr);
// $result is [2, 4, 6]

3. Using ceil and array_map Together to Round Array Elements

By combining these 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 is:

Array
(
    [0] => 2
    [1] => 3
    [2] => 4
    [3] => 4
    [4] => 6
)

Here, array_map directly takes the function name 'ceil' as the callback, and PHP automatically applies ceil to each element in the array.

4. Example Using a Custom Callback Function

If you want to perform additional operations beyond rounding up, you can pass a custom callback:

$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
)

5. Use Cases

  • Uniformly rounding up a list of user input floating-point numbers for easier subsequent calculations or display.

  • Standardizing numerical data during data analysis.

6. Complete Example Code

<?php
// Initialize an array of floats
$floatValues = [0.1, 1.6, 2.3, 3.9, 4.4];
<p>// Use array_map and ceil to round up each element<br>
$ceilValues = array_map('ceil', $floatValues);</p>
<p>// Output the result<br>
echo "<pre>";<br>
print_r($ceilValues);<br>
echo "
";
?>