当前位置: 动力学知识库 > 问答 > 编程问答 >

php - How do I return specific keys from the $_POST array?

问题描述:

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 ( )

网友答案:

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

网友答案:

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!";
  }
}
网友答案:

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

网友答案:

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;
  }
}
网友答案:

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;
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: