Calling array keys with embedded variables

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

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_$business_item_index 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.

Re: Calling array keys with embedded variables

well, not going deep to the cause you could use
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($business_item_index) it should also remove your leading space

Site Timeline