Categories
PHP

Pad and Trim Input Arrays

PHP function to get an input array to have only, and all of the keys specified. This is useful if you have an array of user input with fields as keys, and you want to pad to ensure all keys are present, while stripping any not part of the template array:
[php]<?php
/**
* Fill and strip array according to $keys
* @param array $input
* @param array $keys
* @param mixed $fill
* @return array
*/
function array_purge_fill($input, $keys, $fill = ”) {
$keys = array_flip($keys);
$input = array_intersect_key($input, $keys); //strip extra keys from input

//Add empty values for missing keys
$diff = array_diff_key($keys, $input);
$diff = array_fill_keys(array_flip($diff), $fill);

return array_merge($input, $diff);
}[/php]

Example:

[php]<?php $input = array( ‘name’=>’Mike’, ‘phone’=>’12345’, ‘extra_value’ => true );
$keys = array(‘name’, ‘phone’, ’email’);

$newInput = array_purge_fill($input, $keys);
//has name, phone, email keys. Email will be empty, ‘extra_value’ will be removed[/php]

Leave a Reply

Your email address will not be published. Required fields are marked *