In one of my previous post, I discussed how validate integer variable. However, I recently came across some weird issue while sanitizing an integer. Not sure why its happening like this but this is very confusing. Let's take a look at the following example.
<?php $num = 100; $res = filter_var($num, FILTER_SANITIZE_NUMBER_INT); var_dump($res); ?>
Guess what should the var_dump function return? It will return the following message on your page.
Hmm, I thought the variable num was assigned an integer value. So, why exactly I should be getting a string in return? I understand that the sanitize filter's job is to "remove all characters except digits, plus and minus sign." as per PHP documentation. Does that automatically mean it will return an string? unfortunately, the answer of this question is "yes" and it really doesn't matter if we put the quotation mark or not, it will always return an string.
You can only receive an integer in response only if you define it as such. Here is how.
<?php $num = 100; $res = (int) filter_var($num, FILTER_SANITIZE_NUMBER_INT); var_dump($res); ?>
Now, the response would show you this.
Remember the definition that PHP documentation page provided? Let's put it to the test. Here we go.
<?php $num = "6-2+3p"; $res = filter_var($num, FILTER_SANITIZE_NUMBER_INT); var_dump($res); ?>
and the response is:
As per the documentation, it removes the character "p" and returns rest of the compatible strings. The string count is also "5". This is exactly when it makes sense that why exactly it returned an string instead of an integer at the first place. Perhaps the most bizarre thing happens when you define the filter result to be an integer. Watch this.
<?php $num = "6-2+3p"; $res = (int) filter_var($num, FILTER_SANITIZE_NUMBER_INT); var_dump($res); ?>
You will see the following message on your screen.
Like what the?! it basically slashed out everything after "6"! I thought as per the PHP documentation, the "FILTER_SANITIZE_NUMBER_INT" filter will not remove plus minus and digit?! so, where did the "-2" and "+3" did go? even then negative 2 or positive 3 is an integer by itself!
Well, guess what, when we are assigning a variable with quotation mark it is an string automatically and our filter simply returned the integer as it was defined on our res variable from a string. Understandable but sorta confusing as well, isn't it?