Useful array functions

Small, short code snippets that other people may find useful. Do you have a good regex that you would like to share? Share it! Even better, the code can be commented on, and improved.

Moderator: General Moderators

Post Reply
tores
Forum Contributor
Posts: 120
Joined: Fri Jun 18, 2004 3:04 am

Useful array functions

Post by tores »

Code: Select all

<?php

/**
* Shifts the first element from an array and returns it.&nbsp;
* The internal array pointer is reset by this method,
* but the array keys are left untouched.
* @param array The array to shift from
* @return mixed The shifted element
*/
function array_shift_assoc(&$array) {
   reset($array);
   $key = key($array);
   $removed = $array[$key];
   unset($array[$key]);
   return $removed;
}


/**
* Puts a key - element pair first into an array, while preserving
* the keys.
* @param array The array to shift into
* @param mixed The new key
* @param mixed The new element
* @return int Number of elements in the new array
*/
function array_unshift_assoc(&$array, $key, $element) {
   $array = array_reverse($array, true);
   $array[$key] = $element;
   $array = array_reverse($array, true);
   return count($array);
}


/**
* Splits an array into two parts using a key in the array
* as delimiter. The array given as argument is assigned
* every element after the one indexed by key, while every
* element before and including the one indexed by key is returned.
* If the key isn't in the array, false is returned.
* The keys are preserved.
* @param array The array to split
* @param mixed The delimiter
* @return array Everything before and including the delimiter
*/
function array_split_assoc(&$array, $key) {
	$offset = array_search($key, array_keys($array)) + 1;
	if ($offset === false) {
		return false;
	}
	$removed = array_slice($array, 0, $offset, true);
	$array = array_diff_assoc($array, $removed);
	return $removed;
}
?>
Post Reply