SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Member
    Join Date
    Nov 2004
    Location
    Leicester
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Question Help with escaping a character

    Hi folks,

    Is it possible to escape the [ and ] characters so that they are not interpretted as signifying an array index?

    i.e

    Code:
    PRINT "<type=\"text\" name=\"FIELD_NAME\[".$key."\]\">";
    or would it be;

    Code:
    PRINT "<type=\"text\" name=\"FIELD_NAME\[$key\]\">";
    the form field name should contain the [] symbols but the number in between them is not an array index but just a variable.

    Regards

    Drakash

  2. #2
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Example:

    PHP Code:
    $foo 'FOO';
    $bar 111;

    echo 
    "foo[$bar]";
    // prints foo[111], no need to escape

    echo "$foo[$bar]";
    // doesn't work, undefined offset

    echo "{$foo}[$bar]";
    // prints FOO[111] as expected 

  3. #3
    SitePoint Member
    Join Date
    Nov 2004
    Location
    Leicester
    Posts
    24
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks for your answer, ok then taking that a step further..

    if I had;

    PHP Code:
    $key 0;

    PRINT 
    "<form action=\"test2.php\" method=\"POST\">
    <input type=\"text\" name=\"FIELDNAME[
    $key]\">
    <input type=\"submit\"  name=\"SUBMIT\" value=\"SUBMIT\">
    </form>"

    On test2.php how would I use $_POST to display that form data? would the following work ok?

    PHP Code:
    PRINT "<input type=\"text\" value=\"".$_POST["FIELDNAME[$key]"]."\">"
    NOTE: The form field name has to include the [ and ] (i.e. FIELDNAM[0])

    Cheers

    Drakash

  4. #4
    SitePoint Wizard stereofrog's Avatar
    Join Date
    Apr 2004
    Location
    germany
    Posts
    4,324
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    PHP parses request fields like 'field[key]' into arrays, so if you have

    <input name="field[something]" value="xyz">

    you get $_POST like

    $POST = array('field' => array('something' => 'xyz'));

    As you see there is no $_POST["field[something]"] element, the value must be referred as $POST['field']['something'].

    You find further information on this in php manual (especially "Strings" and "Arrays" sections in "Basic" chapter).


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •