views:

89

answers:

5

I would like to check to see if there are any keys in $_POST that contain a string. The string will not be the full key, only part of the key. (ie. search string = "delRowID", $_POST key = "delRowID_16"). I have tried to use array_keys($_POST,"delRowID"), but it has never returned anything.

CODE

print_r($_POST);
print_r(array_keys($_POST,"delRowID"));

RETURNS

Array ( [delRowID] => 29 [qAction] => [elmUpdateId] => [elmTtl] => [elmDesc] => [elmStr] => ) Array ( )
+2  A: 

Do a loop using array_keys() and check the key with strpos()

foreach (array_keys($_POST) as $key) {
  if (strpos($key, 'delRowId') === 0) {
    echo $key." found!";
  }
}
Mads Jensen
But a loop is a sloppy solution. There has to be a way to accomplish this without an index by index loop.
Brook Julias
@Brook: Yes, by fixing the source of the problem, which is the input being sent. R. Bemrose solution should do the trick.
Mads Jensen
A: 

Loop through the keys provided to you by array_keys($_POST). Do a string match on each.

Also, note that array_keys($_POST,"delRowID") searches for keys that are associated with a value of "delRowID".

Jeff
I guess I misunderstood the search is array_keys(). I thought it was searching through the keys since array_search() searches for matching values and returns the keys.
Brook Julias
A: 

Because you are searching for partial text, you can loop through it:

foreach($_POST as $key => $value)
{
  if (strpos($key, 'delRowID') !== false)
  {
    echo $key;
    break;
  }
}
Sarfraz
+1  A: 

If this is being sent by a form, considering naming the elements as array elements. For example,

<input type="checkbox" name="delRowID[16]" />
<input type="checkbox" name="delRowID[17]" />

would come in as an array named $_POST['delRowID'] with elements for each valid input.

However, this is a contrived example which works better with other input types.

For checkboxes, it would be better done like this, which creates an array with a value for each successful checkbox that you can easily loop over:

<input type="checkbox" name="delRowID[]" value="16" />
<input type="checkbox" name="delRowID[]" value="17" />

See Also: How do I create arrays in a HTML <form>?

R. Bemrose
So if I used delRowID[] as the name of the check boxes the checkboxes returned in $_POST would propagate the array delRowID? This would do exactly what I am looking for.
Brook Julias
@Brook: Yes. In case I missed something, here's the section of the PHP manual which discusses sending values in as an array: http://www.php.net/manual/en/faq.html.php#faq.html.arrays
R. Bemrose
Thanks for your solution.
Brook Julias
A: 

Just another way (extending mads answer):

if( getKey( 'delRowId', $_POST ) ){
    // delRow?
}

function getKey($stringToFind, $array) {
  foreach ($_POST as $key => $val) {
    if (strpos($stringToFind, $key) !== false) {
     return $val;
    } 
  }
  return false;
}
Dan Heberden