There are multiple ways of converting a string to an integer.
$someString = substr($input, strripos($input, "_") + 1);
$i = $someString + 0;
$i = (int) $someString;
$i = intval($someString);
$someString comes from use input, so that might have to be taken into consideration. Which option is “better” or has the most negative side-effects? (i.e. performance-wise, security-wise)
$input can look something like 1_abcd_1 or 1_abcd_2. That is quite fixed — except for the abcd which is made up in this example. This input comes from radio buttons, but a user can always alter their data if they want to. Thus, I have to account for malicious data.
Since the input is being cast to a number, there’s no security issues. Performance differences are negligible. However, the first one may not produce an integer in certain cases.
For example, let
$input = '19.99';.The other two cases are equivalent, but
$i = (int) $someString;averages approximately 56% faster than$i = intval($someString);. Since both execute in a matter of milliseconds, performance differences are generally negligible unless they occur in a sizable loop.On the matter of security: if you expect
$inputto always be in a specific form (e.g. #_xxxx_#), then you should verify that it is in that format. Expanding on Jack’s comment — if you’re using PHP >= 5.2.0, you can check the format of the input using a regular expression.This will completely reject things like:
Naturally, you would adjust the regular expression to your needs.
See also:
If you’re not using PHP >= 5.2.0, you can use preg_match.
Validating the format of the input let’s you know immediately if the data has been tampered with. Then you can act accordingly.