May 10, 2009 at 05:05 PM · Posted under Blog
· Tagged with function
It's fairly general knowledge in PHP that if you want the first item of an array, you can use array_shift. However, this also removes the element from the array and this may not be the intended functionality of the developer. Introducing: array_first.
April 14, 2009 at 03:28 PM · Posted under Blog
· Tagged with function
After having dealt with some directory-creation lately based on user input, I decided to safe-guard the creation of directories with the following function: directorize().
December 09, 2008 at 10:30 AM · Posted under Blog
· Tagged with function
After delving around in ruby for a little and finding the magic that is the Array.collect method, I decided to write one for PHP, considering how much I use it in Ruby. Hopefully others will find some use in this function.
<?php
function array_collect($array, $params)
{
$return = array();
if (!is_array($params)) {
$params = array($params);
}
foreach ($array as $record) {
$rec_ret = array();
foreach ($params as $search_term) {
if (array_key_exists($search_term, $record)) {
$rec_ret[$search_term] = $record[$search_term];
}
}
if (count($rec_ret) > 0) {
$return[] = $rec_ret;
}
}
return $return;
}
?>
Basically, what this allows us to do is extract information from an array and have it stored in another array. For example, we may only want a few select fields as a subset of data, we could do this by doing:
$records = array(array('a' => 'y', 'b' => 'z', 'c' => 'e'), array('a' => 'x', 'b' => 'w', 'c' => 'f'));
$subset1 = array_collect($records, 'a'); // $subset1 will be: array(array('a' => 'y'), array('a' => 'x'));
$subset2 = array_collect($records, array('a', 'c')); // $subset2 will be: array(array('a' => 'y', 'c' => 'e'), array('a' => 'x', 'c' => 'f'));