1

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

1
  • $_POST is an array like others. Commented Nov 12, 2011 at 21:16

2 Answers 2

6

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];
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers for that. I did indeed misunderstand how in_array works! Thanks for setting me straight! R
1

Use the array_intersect function.

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

1 Comment

This creates an array of keys, not an associative array as the OP originally asked for. Try array_intersect_key($_POST, array_flip($textfield_array))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.