1<?php
2
3namespace Mpdf\Utils;
4
5class Arrays
6{
7
8	public static function get($array, $key, $default = null)
9	{
10		if (is_array($array) && array_key_exists($key, $array)) {
11			return $array[$key];
12		}
13
14		if (func_num_args() < 3) {
15			throw new \InvalidArgumentException(sprintf('Array does not contain key "%s"', $key));
16		}
17
18		return $default;
19	}
20
21	/**
22	 * Returns an array of all k-combinations from an input array of n elements, where k equals 1..n.
23	 * Elements will be sorted and unique in every combination.
24	 *
25	 * Example: array[one, two] will give:
26	 * [
27	 *     [one],
28	 *     [two],
29	 *     [one, two]
30	 * ]
31	 * @param array $array
32	 * @return array
33	 */
34	public static function allUniqueSortedCombinations($array)
35	{
36		$input = array_unique($array);
37		if (count($input) <= 1) {
38			return [$input];
39		}
40
41		sort($input);
42		$combinations = [];
43		foreach ($input as $value) {
44			$combinations[] = [$value];
45		}
46
47		$n = count($input);
48		for ($k = 2; $k <= $n; $k++) {
49			$combinations = array_merge($combinations, self::combinations($input, $k));
50		}
51
52		return $combinations;
53	}
54
55	/**
56	 * Returns an array of unique k-combinations from an input array.
57	 *
58	 * Example: array=[one, two, three] and k=2 will give:
59	 * [
60	 *     [one, two],
61	 *     [one, three]
62	 * ]
63	 * @param array $array
64	 * @param int $k
65	 * @return array
66	 */
67	public static function combinations($array, $k)
68	{
69		$n = count($array);
70		$combinations = [];
71		$indexes = range(0, $k - 1);
72		$maxIndexes = range($n - $k, $n - 1);
73		do {
74			$combination = [];
75			foreach ($indexes as $index) {
76				$combination[] = $array[$index];
77			}
78			$combinations[] = $combination;
79
80			$anotherCombination = false;
81			$resetFromIndex = -1;
82			for ($i = $k - 1; $i >= 0; $i--) {
83				if ($indexes[$i] < $maxIndexes[$i]) {
84					$indexes[$i]++;
85					$anotherCombination = true;
86					break;
87				}
88				$resetFromIndex = $i;
89			}
90
91			if ($resetFromIndex > 0) {
92				for ($i = $resetFromIndex; $i < $k; $i++) {
93					$indexes[$i] = $indexes[$i - 1] + 1;
94				}
95			}
96		} while ($anotherCombination);
97
98		return $combinations;
99	}
100}
101