Unexplained use of (int) conversion

I am reading a book and it contains the following line of code :

call_user_func("processStep" . (int)$_POST["step"])

What is the purpose of using (int) conversion here?

The int call casts it as an integer. It is likely that the developer is expecting a number and is doing this to ensure he gets one.

Note that it is not wise to type cast a variable that comes from user input.

It is best to first check if the variable could be an int before actually casting it as such. Otherwise, if the variable ends up not being an int and is then type cast, you could end up with a bug or error.

The value comes from an input hidden tag like this :

<input type="hidden" name="step" value="2">

My question is why we should convert this $_POST[“step”] to int before the concatenation.

Because I could modify that value to something like:

<input type="hidden" name="step" value="MESSEDUPYOURSTUFF">

Than an error will occur in attempting to call undefined function.

That practice though is really more applicable to avoiding SQL injection. Anything that is not an integer would be cast to 0.

It could also be messed up with something like this:

<input type="hidden" name="step" value=""100000">

So one could argue that without checking whether the function exists before calling it makes the cast kinda worthless.


$name = 'processStep' . $_POST["step"];

if(function_exists($name)) {

Thank you for your clear explanation oddz.

I find it a little silly that he’s even using the hidden type to submit this through POST.

Great explanation @oddz;

By using (int) you know exactly what you are going to get, either a positive integer or 0.

It all comes down to how you have presented options to a user on a form on your site.

a) Did you give them a pick list of numbers to pick from, or a pre-defiined element with a set integer (usually a hidden field with an id)


b) Did you give them a text box into which they can enter just about anything, but your GUI hints specify a number.


If you do not get an integer, does that mean they:

  1. could have made a mistake


  1. altered a copy of the html and re-submitted it

If you did not get an integer after :

a) then 1) – this is not possible without tampering, same as a) then 2) – this is bad

a) then 2) – this is bad

b) then 1) – then you should question your motives, or be kind an throw back an error msg.

b) then 2) – this is bad

So, when you are expecting an integer, and after typecasting it equates to 0 then this is generally a bad sign, and you should abort and get rid of the user.

As a developer it is also very easy to use and recall, that is why you will see it again and again.

Just a small clarification: integers can also be nagative :slight_smile: