Page 1 of 1

array key with space issue

Posted: Wed Dec 22, 2010 12:51 pm
by tomindo

Code: Select all

echo "<input type=checkbox name=b[$a] value=1>view,";
I m trying to submit array b, it works fine if $a is string without space but string with space like "my name". That is really weird

Re: array key with space issue

Posted: Wed Dec 22, 2010 1:00 pm
by Technical
tomindo wrote:

Code: Select all

echo "<input type=checkbox name=b[$a] value=1>view,";
I m trying to submit array b, it works fine if $a is string without space but string with space like "my name". That is really weird
Use single quotes, like

Code: Select all

echo "<input type=\"checkbox\" name=\"b['".$a."']\" value=\"1\">view,";

Re: array key with space issue

Posted: Wed Dec 22, 2010 1:10 pm
by tomindo
thanks man
why did that happen, btw?

Re: array key with space issue

Posted: Wed Dec 22, 2010 1:32 pm
by Technical
tomindo wrote:thanks man
why did that happen, btw?
Because if there is no quotes PHP can't "guess" where does string ends. Space separates language tokens.

Re: array key with space issue

Posted: Wed Dec 22, 2010 6:36 pm
by McInfo
Technical wrote:PHP can't "guess" where does string ends.
Actually, the problem occurs in HTML. Whitespace separates element attributes in HTML. Without quotes, the second word becomes a new attribute.

Here is an example with PHP and the resulting HTML.

Code: Select all

$a = 'box checked';
echo "<input type=checkbox name=b[$a] value=1>view,";

Code: Select all

<input type=checkbox name=b[box checked] value=1>view,
The input element has four attributes: type, name, checked], and value.

Code: Select all

<input type="checkbox" name="b[box" checked]="" value="1">