Container utility class

The [Container](NoreSources/Container) class provides a common API to manipulate and query most common container types such as array, ArrayAccess, Psr/ContainerInterface, or Traversable.

All methods of these class are static and expect the first argument to be a container type or object.

Container properties

The Container::getContainerProperties($container) provides informations on container type capabilities.

A container can be

  • MODIFIABLE : Key values can be changed.
  • EXTENDABLE: New key-value pair can be added th the container.
  • SHRINKABLE: Elements can be removed from container.
  • RANDOM_ACCESS: Container elements can be accessed using random access method or bracket operator.
  • TRAVERSABLE: The container can be iterated with the foreach statement.
  • COUNTABLE:

The various Container::is*() functions provides shorthands and extended informations.

Container access

The Container::keyValue($container, $key, $defaultValue) is a generic way to get the value of a given key or fallback to the default value if the key does not exists.

$a = ['a', 'b', 'c'];
if (($letter = Container::keyValue (1, $a, false) !== false) // $value == 'b'
	echo 'Yeah !';

Advanced operations

implode*() functions extends the built-in implode() function by providing more control on how keys and values are formatted.

$source = [
	0 => 'zero',
	1 => 'one',
	2 => false,
	3 => 'three',
	4 => false,
	5 => false,
	7 => 'seven'
];

$glue = [
	'before' => '[', // Prefix added before each selected element
	'after' => ']',  // Suffix added after each selected element
	'between' => ', ', // String inserted between eeach element but the last
	'last' => ' and '  // String inserted between the penultimate and last element
];
$stringValues = Container::implodeValues($source, $glue,
	function ($v) {
		if ($v === false)
			return false;
		return strval($v);
	});
var_dump ($stringValues); // "[zero], [one], [three] and [seven]";

Performances

Traversal-based process functions such as Container::filter() and Container::implode() have obviously an order of O(n) (with n, then number of keys of the container).

Random-access based functions such as Container::keyValue() are generally wrappers around built-in functions, conditionally called according input container type. However, when the input container does not provide random-access capabilities, a full traversal of the container will be done in the worst case.

Container::isIndexed()' and Container::isAssociative()` will also iterate all the container elements in the worst case.