_.pick is great
Underscore.js has a lot of great stuff packed in it. One of the functions I love is pick, which lets you input some keys and get a new array from an Array.
Can’t pick in PHP
So today I wanted to find an alternative to Underscore’s _.pick for PHP, and I didn’t. It’s not a function that would be difficult to write, but that’s where WordPress comes in.
Can pick in WordPress
People at WordPress thought that it would be a nice helper for them too, so in WordPress 3.1 they added
The naming is a bit long, but the function is awesome anyway and the naming explains the purpose alright. Slice an array associativley ( that’s a big word ).
Here is how it works.
Imagine we have a some array like this one.
'a name', 'jane' => 'also a name', 'doe' => 'a fake last name', 'duck' => 'an animal', 'goose' => 'an animal', ); ?>
In this case the array is a mess, your array should never be a mess, but it might happen. In this case, I know I want only John and Jane in my array, so I can do this:
$persons = wp_array_slice_assoc( $myray, array('john', 'jane') );
Tara. Now I have a new array “$persons” which has only john and jane.
How is this useful ?
Well, there are times where you would write something like this:
$john = $myray['john']; $jane = $myray['jane']; $duck = $myray['duck']; $goose = $myray['goose'];
Which I think of an overkill, especially if you need like 10 variables. Of course you could extract from all of them
But what if the array has like 20 items. What happens when they clash? What if someone else modifies your code? I just don’t feel that blindly using extract is the best development pattern.
Along comes wp_array_slice_assoc()
$keys_to_extract = wp_array_slice_assoc( $myray, array( 'john', 'jane', 'duck', 'goose' ) ); extract( $keys_to_extract );
Or a slightly more readable (based on preference) variant
$keys_to_extract = array( 'john', 'jane', 'duck', 'goose' ); extract( wp_array_slice_assoc( $myray, $keys_to_extract ) );
echo $john; // Echoes: "a name"
Please, please be careful extracting variables. And when you do, please document them, even if the documentation comes in the form of
$keys_to_extract. Recently I had a very difficult time figuring out what is what because the author of a plugin pulled some weird variables out of nowhere and I had to run around var_dump’ing all over the place until I figured out what is what.