Whitelist and Blacklist Array Keys in PHP

Two utility functions you will definitely want to add to your arsenal would be array_keys_whitelist() and array_keys_blacklist().

First, array_keys_whitelist() will ensure that only specific items in an associative array are allowed:

/**
 * Filter an array based on a white list of keys
 *
 * @param array $array
 * @param array $keys
 *
 * @return array
 */
function array_keys_whitelist( array $array, array $keys ) {
   foreach ( $array as $key => $value ) {
      if ( ! in_array( $key, $keys ) ) {
         unset( $array[ $key ] );
      }
   }

   return $array;
}

This function is useful for things like returning a specific set of values from the global $_POST array.

On the other hand, the array_keys_blacklist() function will ensure that all disallowed items in an associative array are removed:

/**
 * Filter an array based on a black list of keys
 *
 * @param array $array
 * @param array $keys
 *
 * @return array
 */
function array_keys_blacklist( array $array, array $keys ) {
   foreach ( $array as $key => $value ) {
      if ( in_array( $key, $keys ) ) {
         unset( $array[ $key ] );
      }
   }

   return $array;
}

While it is typically better to whitelist than to blacklist, this function can be useful when you need to create an exception to a rule.


Update: August 28th, 2015

I’ve recently realized that the array_keys_whitelist can be written in a shorter fashion and without the foreach loop. I’d imagine that would make it faster, but haven’t tested it. Here is the more succinct version:

/**
 * Filter an array based on a white list of keys
 *
 * @param array $array
 * @param array $keys
 *
 * @return array
 */
function array_keys_whitelist( array $array, array $keys ) {
   return array_intersect_key( $array, array_flip( $keys ) );
}

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.