I started programming, for a few years, in php 3 way back in 1998 and I remember that I could pass variables with an index from an html form, like this:
<form action="call.php" method="post">
<input name="text[0]" type="text">
<input name="text[1]" type="text">
<input name="text[2]" type="text">
...
<input name="text[9]" type="text">
<button type="submit" value="Go">Go</button>
</form>
in my call.php page I could treat variables exactly as if I had an array, like this:
<?
for($n = 0; $n < 10; $n ) {
echo $text[$n] . '<br>';
}
?>
After about 22 I wanted to take a look at the changes that php has had and its evolution (so I'm talking about version 8) and I noticed that, in particular on passing values in an html form, once the variables are passed, these must be handled via $_POST or $_GET (depending on whether they were passed via POST or GET method respectively). So, I told myself, code like the following will satisfy my request to pass indexed variables:
<?
for($n = 0; $n < 10; $n ) {
$newtext[$n] = $_POST['text'][$n];
echo $newtext[$n] . '<br>';
}
?>
but i didn't get what i was looking for so i tried with:
<?
for($n = 0; $n < 10; $n ) {
$newtext[$n] = $_POST['text[$n]'];
echo $newtext[$n] . '<br>';
}
?>
but even with this system I have not been successful. Do any of you know if it is still possible to send variables this way?
Update: Using the type = "file" attribute from an html data request form similar to this:
<input name = "nome_file[]" type = "file">
<input name = "nome_file[]" type = "file">
etc. It seems that the size_of function doesn't really like the file type, in fact I am left with this error:
Warning: sizeof(): Parameter must be an array or an object that implements Countable in ...
So I thought, just to see how it actually works, give a series of instructions like this:
for($n = 0; $n < 10; $n ) {
if(!isset($_POST['nome_file'][$n])) {
$nome_file[$n] = $_POST['nome_file'][$n];
$fileName = basename($_FILES["nome_file[$n]"]["name"]);
echo "--" . $fileName . '<br>';
}
}
But I don't get the filename.
CodePudding user response:
Welcome back :)
First thing you need to know is that short open tags are removed in 8.0. So you need to use the standard open tags
<?php ... ?>
And yes PHP still allows us to pass HTML forms as an array, but you need to know the size of the array to loop through and you don't actually have to pass indexes to it like text[0], text[9] you can just do this
<input name="text[]" type="text">
<input name="text[]" type="text">
<input name="text[]" type="text">
Now handle the request
// If HTTP method type is POST
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// sizeof to get the size of text array
for ($n = 0; $n < sizeof($_POST['text']); $n ) {
$newtext[$n] = $_POST['text'][$n];
echo $newtext[$n] . '<br>';
}
}
Or you can use foreach
foreach ($_POST['text'] as $value) {
echo $value, "<br/>";
}