7

In PHP, can a value from the global $_POST array be something else than an array or a string?

The goal is to not have to check if everything is something else than an array or string in a script. If I know what type a variable has, I don't have to do some weird validation. If I expect a string, I don't have to cast everything to a string to make sure it is one.

6
  • 5
    something else? what did you have in mind
    – Nick
    Feb 19, 2013 at 14:49
  • 3
    Instead of playing a guess-game, explain the reason for your question and what you would like to achieve.
    – CodeCaster
    Feb 19, 2013 at 14:51
  • 1
    possible dupe stackoverflow.com/questions/5052932/… Feb 19, 2013 at 14:52
  • The goal is to not have to check if everything is something else than an array or string in a script. If I know what type a variable has, I don't have to do some weird validation. Feb 19, 2013 at 14:54
  • 1
    You should always do input validation.
    – CodeCaster
    Feb 19, 2013 at 14:54

3 Answers 3

5
$_POST["key"] = true;

var_dump($_POST["key"]); // bool(true)

The values set by the environment are strings though.

4

As per the documentation http://php.net/manual/en/reserved.variables.post.php

An associative array of variables passed to the current script via the HTTP POST method. 

So all the data sent is in associative array, in key value pair. There are Numbers (int, float etc), Strings, Arrays (of numbers or strings) and Objects data types.

Using the rule of elimination we can remove the Object from the supported data type, and the remaining left are strings, numbers and array.

Now, if you see the form, the input fields are taking strings, there is no indication that the value entered in the input field is number or string. So to be on safe side all the values which are posted are in strings. The array of elements also have the string values.

When you get the value in $_POST it is simply an array and you can override it any time

$_POST['username'] = 1;
var_dump($_POST['username']); // int (1)

I hope this make some sense

2

You can cast it to whatever you wish ^^

intval($_POST['INTEGER']);
or simply
 (int)$_POST['int']
1
  • 3
    Casting the value to something else than a string is different from the value being different from a string. This doesn't really answer the question.
    – Jørgen R
    Feb 19, 2013 at 14:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.