This tutorial will discuss multiple ways to check if string can be converted to int in PHP.
Table Of Contents
Method 1: Using is_numeric() function
To check if a string can be converted into an integer, we can follow the following steps:
First, we need to pass the string into the is_numeric() function. It will return true, if the string contains a numeric value. However, it’s important to note that is_numeric() can also return true for non-defined variables. Therefore, after this check, we should perform additional validation.
After checking with is_numeric(), we can use the intval() function. It accepts the string as an argument and returns the corresponding integer value. By calling intval() on the string, we can ensure that the conversion is successful. If both is_numeric() and intval() return true, it indicates that the string can be converted into an integer.
Let’s see the complete example,
<?php /** * Check if a string can be converted to an integer. * * @param string $strValue The string to validate. * @return bool True if the string can be converted to an integer, false otherwise. */ function isConvertibleToInt($strValue) { return is_numeric($strValue) && intval($strValue) == $strValue; } $strValue = '815'; // Check if string can be converted to an integer if (isConvertibleToInt($strValue)) { echo "Yes, the string can be converted to an integer."; } else { echo "No, the string cannot be converted to an integer."; } ?>
Output
Frequently Asked:
Yes, the string can be converted to an integer.
Method 2: Using filter_var() function
PHP provides the filter_var() function, which can be used with the FILTER_VALIDATE_INT filter to check if a string can be converted into an integer.
To utilize this, we pass the string as the first argument and FILTER_VALIDATE_INT as the second argument. If filter_var() returns true, it means that the string can be converted into an integer.
Let’s see the complete example,
<?php /** * Check if a string can be converted to an integer. * * @param string $strValue The string to validate. * @return bool True if the string can be converted to an integer, false otherwise. */ function convertibleToInt($strValue) { return filter_var($strValue, FILTER_VALIDATE_INT) !== false; } $strValue = '915'; // Check if string can be converted to an integer if (convertibleToInt($strValue)) { echo "Yes, the string can be converted to an integer."; } else { echo "No, the string cannot be converted to an integer."; } ?>
Output
Yes, the string can be converted to an integer.
Summary
Today, we learned about multiple ways to check if string can be converted to int in PHP.