array key with space issue

Questions about the MySQL, PostgreSQL, and most other databases, as well as using it with PHP can be asked here.

Moderator: General Moderators

Post Reply
tomindo
Forum Newbie
Posts: 13
Joined: Sun Mar 21, 2010 1:22 am

array key with space issue

Post 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
User avatar
Technical
Forum Commoner
Posts: 81
Joined: Thu Dec 02, 2010 5:30 am

Re: array key with space issue

Post 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,";
tomindo
Forum Newbie
Posts: 13
Joined: Sun Mar 21, 2010 1:22 am

Re: array key with space issue

Post by tomindo »

thanks man
why did that happen, btw?
User avatar
Technical
Forum Commoner
Posts: 81
Joined: Thu Dec 02, 2010 5:30 am

Re: array key with space issue

Post 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.
User avatar
McInfo
DevNet Resident
Posts: 1532
Joined: Wed Apr 01, 2009 1:31 pm

Re: array key with space issue

Post 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">
Post Reply