tags:

views:

65

answers:

3

Which of the following ways is the right one in using the characters " and ' inside PHP's sub-arrays?

#1 Way in debugging PHP code

$_POST["login['username']"];

#2 My original way in PHP

$_POST['login[username]'];

My code is now broken after changing all my variables to arrays.


The following is the HTML to which the variables refer.

<p>Username:
         <input name="login['username']" type="text" cols="92" />
     </p>

     <p>Email:
         <input name="login['email']" type="text" cols="92" />
     </p>

     <p>Password:
         <input name="login['password']" type="password" cols="92" />
     </p> 

     <input type="submit" value="OK" />
 </form>

Which one is the right way of the following ways in using arrays in HTML.

#11

<input name="login['password']" type="password" cols="92" />

#22

<input name="login[password]" type="password" cols="92" />

I am at the moment using the ways #1 and #11 unsuccessfully?

+6  A: 

You don't need to quote the array keys in HTML, this is correct:

<input name="login[password]" type="password" cols="92" />

This will create in $_POST a key 'login' whose value is another array having the key 'password', so you can access it like:

$_POST['login']['password']
Tom Haigh
+2  A: 

First of all, the correct form in html is what you have for #22 (no quotes).

Secondly, the entire point of doing this is because it will convert it into an array. When this form is posted, an array is created INSIDE of $_POST called login. To access it, try this:

echo $_POST['login']['username']; //echos username
echo $_POST['login']['password']; //echos password

Here's a quick overview of how the nesting looks:

'_POST' =>
    array
      'login' => 
        array
          'username' => string 'myusername' (length=10)
          'password' => string 'mysecretpassword' (length=16)

Try doing this to get a good idea of what's going on and get output like above:

echo "<pre>";
var_dump($_POST);
echo "</pre>";

You'll be able to see all the nesting.

ryeguy
I get this `Array ( [login] => Array ( [email] => )` for this `$_SESSION['login']['email'] = "ntohuh";`? **Do you know why I do not see the value?**
Masi
I opened a new thread based on this answer at http://stackoverflow.com/questions/1275916/to-understand-php-sessions-with-sub-arrays-better
Masi
A: 

just give your variables normal names: username, password and email. you're creating your own problem.

SilentGhost