简体   繁体   中英

PHP in_array for $_POST

I hope this isn't too vague a question, but here goes.

I want to loop through the values stored in the textfield_array and see if they match any keys in the $_POST array. If they do I want to assign them to the an_array array.

It seems that there are no matches, although I know that there should be! Here's my code:

<?php
$an_array = array();

$textfield_array = array(
 'item_no', 'button_text', 'text_field', 'drop_down_title'
);

foreach( $textfield_array as $textfield ){
  if( in_array( $textfield, $_POST ) ){
    $an_array[$textfield] = $_POST[$textfield];
  }
}
?>

Am I being daft? Or misunderstanding how the $_POST array works?!

You are misunderstanding how in_array works. in_array checks the values. You want to check the keys.

You can either use isset , or you can use array_key_exists (returns true if item exists with a value of null ).

foreach ($textfield_array as $textfield) {
    if (isset($_POST[$textfield])) {
        $an_array[$textfield] = $_POST[$textfield];
    }
}

使用array_intersect函数。

$an_array = array_intersect(array_keys($_POST), $textfield_array);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM