Richard Sweeney
Richard Sweeney

Reputation: 782

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

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 $_POSTarray works?!

Upvotes: 1

Views: 1023

Answers (2)

igorw
igorw

Reputation: 28249

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];
    }
}

Upvotes: 6

Jim H.
Jim H.

Reputation: 5579

Use the array_intersect function.

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

Upvotes: 1

Related Questions