In PHP, the ceil() function is used to round a number up. It returns the smallest integer greater than or equal to the specified number. For example:
echo ceil(4.3); // Output 5
But what happens if we pass null or false, which are not numeric values? This article will explore these edge cases in detail.
ceil() requires one parameter, which should be a numeric type (int or float). When the function is called, PHP automatically performs type conversion (type casting), attempting to convert the passed value into a number.
When the ceil() function receives null as a parameter, PHP converts null into the number 0 and then rounds it up.
Example code:
echo ceil(null); // Output 0
Explanation:
null is converted to the number 0
ceil(0) equals 0
Similarly, when passing false, PHP will also convert it into a number. false is converted to the number 0, and then ceil() is called.
Example code:
echo ceil(false); // Output 0
Explanation:
false is converted to the number 0
ceil(0) equals 0
For completeness, let's look at the result when passing true:
echo ceil(true); // Output 1
Here, true is converted to the number 1, and ceil(1) remains 1.
As an additional note, passing an empty string also behaves similarly:
echo ceil(""); // Output 0
An empty string is also converted to the number 0.
Input Value | Converted to Number | ceil() Output |
---|---|---|
null | 0 | 0 |
false | 0 | 0 |
true | 1 | 1 |
"" (empty string) | 0 | 0 |
Conclusion: When null or false is passed, ceil() processes them as the number 0, and the returned value is 0. This behavior is due to PHP's type conversion mechanism.
<?php
<p>$values = [null, false, true, "", 3.7];</p>
<p>foreach ($values as $val) {<br>
echo 'ceil(' . var_export($val, true) . ') = ' . ceil($val) . PHP_EOL;<br>
}</p>
<p>/*<br>
Output:<br>
ceil(NULL) = 0<br>
ceil(false) = 0<br>
ceil(true) = 1<br>
ceil('') = 0<br>
ceil(3.7) = 4<br>
*/<br>
We hope this article helps you better understand how the ceil() function behaves when null and false are passed in PHP.
If you're interested in PHP's type conversion mechanisms, it's recommended to dive deeper into PHP's type casting rules.