I have a form that takes in data and writes to a JSON form in PHP.
I needed to submit an array as a numeric input but it keeps giving me a string. Is it possible to enable the form to submit as an array via text input box?
Form example:
<input type="text" name="arraytobepushed[]" placeholder="EG: 1000,2000,3000" />
The output is:
{
"obj": [{
"arraytobepushed": ["1000,2000,3000"]
}]
}
You could turn the text into an array by using explode()
So you would have something like this:
<?PHP
$myArray = explode(',', $_POST['arraytobepushed[]']);
?>
The explode()
function splits everything separated by the first argument (in this case a comma) you pass and puts it into an array.
So if your inputted was 1000, 2000, 3000
your $myArray
would look like:
index 0 = "1000" ( $myArray[0]
)
index 1 = "2000" ( $myArray[1]
)
index 2 = "3000" ( $myArray[2]
)
Keep in mind that the values are still strings, not integers. If you want to make them integers you can do this:
$myArray = array_map('intval', explode(',', $_POST['arraytobepushed[]']));
This makes all your elements into integers like so:
index 0 = 1000 ( $myArray[0]
)
index 1 = 2000 ( $myArray[1]
)
index 2 = 3000 ( $myArray[2]
)
No. Forms submit text.
PHP special cases fields with []
in the name as fields to be expressed in an array. It has no special case feature to treat a field as a number instead of a string. You need to convert the data explicitly.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.