Calling array keys with embedded variables

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • jingalls

    Calling array keys with embedded variables

    Hello,

    I'm in the middle of modifying a script and I've come across a problem.
    I have a form that gets repeated x number of times and each field in
    the form gets the name $item_number_ . $business_item_ index ._(the
    specific field name). These varaibles get reposted to the same page as
    $_POST variables, so that the forms save the users settings. What I'm
    trying to do is parse through those fields that the user did not set,
    and if they are null, to unset them and decrement the counter
    ($business_item _index) so that one less form gets written to the screen
    the next time the user submits.

    My problem is that when I parse through them like this:

    if ($_POST['item_number_'. $business_item_ index.'_title'] == NULL){
    unset ($_POST['item_number_'. $business_item_ index.'_title']);
    $business_item_ index --;
    }

    Php sees that variable key I'm calling as
    item_number_ 1_title
    even though I defined $business_item_ index as a variable and it works
    just fine if I decrement or increment it.

    Note the white space after "number_". I can't figure out why php is
    prepending a space to my integer.

    My actual code is alot more complicated than this, because I'm doing a
    foreach statement and splitting the $_POST global array into key =
    value and then unsetting all the keys that have
    item_number_$bu siness_item_ind ex as a substr($key, 0,13), so that all
    of the fields for that business item form gets unset. But I think the
    above example is sufficient to explain the problem. If you need to see
    a more detailed code block I can post it.

    Thanks for any assistance.

  • Sergej Andrejev

    #2
    Re: Calling array keys with embedded variables

    well, not going deep to the cause you could use
    trim($business_ item_index)
    to get rid of first and last spaces if $business_item_ index is a string
    after all or you could try to convert string to int like this
    intval($busines s_item_index) it should also remove your leading space

    Comment

    Working...