开发者

Most efficient, safe way of dealing with a large number of $_REQUEST variables in php

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 adva开发者_运维技巧nce for your help.


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 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜