kirk bushell | Riding the wave of programmatic novelty

Archive for tag Function

Retrieve the First Element of an Array

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.

directorize() 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().

array_collect, mapping required fields to a PHP array

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'));