Current Location: Home> Latest Articles> Can the ceil() function in PHP handle numbers in string format?

Can the ceil() function in PHP handle numbers in string format?

M66 2025-06-23

Basic usage of the ceil() function

ceil() function's basic syntax is as follows:

ceil(float $num): float  

This function accepts a numeric parameter and returns the smallest integer greater than or equal to the given number. For example:

echo ceil(3.2); // Output 4  

Numbers in string format

In PHP, strings are automatically converted to numeric types during mathematical operations. That is, if you pass a string that can be parsed as a floating-point number, ceil() will work as expected:

echo ceil("4.7"); // Output 5  
echo ceil("10"); // Output 10  

This is particularly useful when handling form inputs or GET parameters:

$price = $_GET['price']; // URL: https://m66.net/product.php?price=9.3  
echo ceil($price); // Output 10  

Even if $_GET['price'] is a string, as long as its format is valid, ceil() will function properly.


What happens with invalid strings?

If the passed string cannot be converted to a numeric value, PHP will treat it as 0 and trigger a warning:

echo ceil("abc"); // Output 0 and trigger a PHP warning  

Similarly, for mixed characters (like "12abc"), PHP will parse from left to right until it encounters a non-numeric character:

echo ceil("12abc"); // Output 12  

Although PHP's lenient design helps prevent crashes, it does not mean we should rely on it for error handling. A better approach is to use is_numeric() to check first before processing:

$input = $_GET['amount']; // https://m66.net/order.php?amount=3.8  
<p data-is-last-node="" data-is-only-node="">if (is_numeric($input)) {<br>
echo ceil($input);<br data-is-only-node="">
} else {<br>
echo "Invalid input";<br>
}<br>