Mask Array Function - for setting default array structures and masking


/ Published in: PHP
Save to your folder(s)

Summary
=======
A useful function for masking arrays. Very useful if you have a function or method that takes arguments in an array, and you would like to force that array to have a specific structure.

Its also great for setting defaults due to the fact that whatever structure or variables that are missing from the arguments array, and are present in the default (mask) array will be copied from the default array and merged into the returned array.

Description
========

**mask_array**( array $defaults , array $arguments [, bool $keep_unset ] )

Accepts two arrays. The first array is used as a mask on the second array.


Parameters
========

**$defaults** - An array of defaults to use as a mask.
**$arguments** - An array of arguments to be filtered by the mask array.
**$keep_unset** - Setting this to true disables discarding variables and structure that will not fit within the mask.

Example
======

/*
* Basic use case
*/

$defaults = array(
'colour' => 'red',
'shape' => 'circle'
'size' => 'large'
);

$arguments = array(
'colour' => 'blue'
'wooden' => true
);

$filtered = mask_array($defaults, $arguments) ;

Result
====

**$filtered** will look like this:

array(
color => blue,
shape => circle,
size => large
)

Note that the key 'broken' is discarded, while the color is carried over.

If the third argument is set to true the result would be the following:

array(
color => blue,
shape => circle,
size => large,
wooden => true
)

Note that because keep unset is true the mask does not cut out the key 'broken' is included.

Hope that you find this useful

~Robert Hurst

URL: http://thinktankdesign.ca/

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.