user2316667
user2316667

Reputation: 5634

What is 'name="array[]" in the checkbox input declaration of an html/php script?

In a 'learn mysql' book I'm following there is the following line (simplified... It gets data from a server and does other stuff but I edited it so the main part to focus on is there).

<input type="checkbox" value="1" name="todelete[]" />

What does it do and is there a name for this kind of syntax? I'm guessing we don't refer to is like $_POST[todelete[]]

The book uses it in a foreach loop:

foreach ($_POST['todelete'] as $delete_id)

I can't pin my finger on it... but something about this isn't clicking in terms of how I've used the name attribute in the past.

Upvotes: 0

Views: 3058

Answers (2)

Ian Atkin
Ian Atkin

Reputation: 6366

It's simply declaring an array to accept multiple answers.

Furthermore, you can use a multi-dimensional array in a form input:

HTML:

<input name="data[customer][firstname]" type="text" />
<input name="data[customer][lastname]" type="text" />

PHP:

$firstname = $_POST['data']['customer']['firstname'];

In your example, the data would be stored in $_POST as...

$_POST['todelete']

...which would be an array of checkbox values.

In order for the foreach to make sense, you would need to know something about the checkboxes in question in order to do something useful with the data. You could just as easily use...

$post = $_POST['todelete'];

$post[0]
$post[1]
... etc.

Especially useful is the way that PHP can handle indexed form names. For example, you could have...

<input name="employee[0][firstname]" value="John"/>
<input name="employee[0][lastname]" value="Smith"/>

<input name="employee[1][firstname]" value="Joe"/>
<input name="employee[1][lastname]" value="Bloggs"/>

And it will return an array of values as $_POST['employee']...

array (
    0 => array('firstname' => 'John', 'lastname' => 'Smith'),
    1 => array('firstname' => 'Joe', 'lastname' => 'Bloggs'),
)

Upvotes: 2

elclanrs
elclanrs

Reputation: 94141

It's just an array, and it's interpreted as an array in PHP. You wouldn't access the array like foo[arr[]], but like foo['arr'] which will give you the array to loop. Think of this for example:

$post = array('todelete' => [1,2,3,4]);
$todelete = $post['todelete'];
var_dump($todelete); //=> [1,2,3,4]

Upvotes: 1

Related Questions