tags:

views:

38

answers:

2

I have a form that submits a large number of inputs...

<input type="hidden" name="searchTag_happy" value="0" />
<input type="hidden" name="searchTag_sad" value="0" />
<input type="hidden" name="searchTag_ambivalent" value="0" />
etc
.
.
.

The value attributes for these inputs can be either "0" or "1".

I would like to use this information to create an array "searchTags" that contains any attributes whose values are set to "1".

I'm wondering what is the most efficient, safe method for dealing with this in php. Currently I have a long list of if statements like so...

if ($_REQUEST['searchTag_happy']) $searchTagArray[] = "happy";
if ($_REQUEST['searchTag_sad']) $searchTagArray[] = "sad";
if ($_REQUEST['searchTag_ambivalent']) $searchTagArray[] = "ambivalent";
etc
.
.
.

But that seems very verbose. Is there a better alternative?

Thanks in advance for your help.

+2  A: 
foreach($_REQUEST as $k=>$req)
{
   if(strpos($k,"searchTag_")!==false && $req)
   {
       $searchTagArray[]=$req;
   }
}

In this way you loop through the REQUEST array and get only values with a key that contains "searchTag_" and with value=1

mck89
A: 

Mck89 is nearly right - to get the required array:

foreach($_REQUEST as $k=>$req)
{
   if(strpos($k,"searchTag_")!==false && $req)
   {
       $searchTagArray[]=substr($k,10);
   }
}

But given that the numbering of the array is not relevant then it rather implies that the resultant data structure may not be optimized - a better solution might be:

       $searchTagArray[substr($k,10)]=1;

Or just use array_filter() to return the non-zero values without translating the keys.

C.

symcbean
Thanks for the response. In regards to this: "But given that the numbering of the array is not relevant then it rather implies that the resultant data structure may not be optimized." Thanks for the heads up. I have modified the code to compile a string instead of an array, like so: $searchTags .= substr($k,10).";";
Travis