I'm trying to do the following:
Grab key/value pairs from an array
$post_data...Only where the key matches a provided list
$my_fields...And create a new array with only the matched data.
For example, from $post_data I'd like to grab the key/value pairs for first_name, last_name, and title while ignoring user_email. I'd then like to create a new array named $clean_data with these key/value pairs.
Below is my failed attempt at looping through the $post_data array and pulling out the matches based on the $my_fields array.
// These are the fields I'd like to get from the $post_data array
$my_fields = array(
'first_name',
'last_name',
'title'
);
// This is the raw data. I do not need the 'user_email' key/value pair.
$post_data = array(
'first_name' => 'foo',
'last_name' => 'bar',
'title' => 'Doctor',
'user_email' => '[email protected]'
);
$clean_data = array();
$counter == 0;
foreach ($post_data as $key => $value)
{
if (array_key_exists($my_fields[$counter], $post_data))
{
$clean_data[$key] = $value;
}
$counter++;
}
// Incorrectly returns the following: (Missing the first_name field)
// Array
// (
// [last_name] => bar
// [title] => Doctor
// )