xref: /plugin/combo/ComboStrap/ArrayUtility.php (revision 37748cd8654635afbeca80942126742f0f4cc346)
1<?php
2
3
4namespace ComboStrap;
5
6
7use DateTime;
8
9class ArrayUtility
10{
11
12    /**
13     * Print recursively an array as an HTML list
14     * @param array $toPrint
15     * @param string $content - [Optional] - append to this variable if given
16     * @return string - an array as an HTML list or $content if given as variable
17     */
18    public static function formatAsHtmlList(array $toPrint, &$content = "")
19    {
20        /**
21         * Sort it on the key
22         */
23        ksort($toPrint);
24
25        $content .= '<ul>';
26        foreach ($toPrint as $key => $value) {
27            if (is_array($value)) {
28                $content .= '<li>' . $key . ' : ';
29                self::formatAsHtmlList($value, $content);
30                $content .= '</li>';
31            } else {
32                if (preg_match('/date|created|modified/i', $key) && is_numeric($value)) {
33                    $value = date(DateTime::ISO8601, $value);
34                }
35                $stringValue = var_export($value, true);
36                $content .= '<li>' . $key . ' : ' . $stringValue . '</li>';
37            }
38        }
39        $content .= '</ul>';
40        return $content;
41    }
42
43    /**
44     * Delete from an array recursively key
45     * that match the regular expression
46     * @param array $array
47     * @param $pattern
48     */
49    public static function filterArrayByKey(array &$array, $pattern)
50    {
51        foreach ($array as $key => &$value) {
52            if (preg_match('/' . $pattern . '/i', $key)) {
53                unset($array[$key]);
54            }
55            if (is_array($value)) {
56                self::filterArrayByKey($value, $pattern);
57            }
58        }
59    }
60
61    public static function addIfNotSet(array &$array, $key, $value)
62    {
63        if (!isset($array[$key])) {
64            $array[$key] = $value;
65        }
66    }
67
68    /**
69     * @param $array
70     * @return int|string|null - the last key of an array
71     * There is a method {@link array_key_last()} but this is only available on 7.3
72     * This function will also reset the internal pointer
73     */
74    public static function array_key_last(&$array)
75    {
76        // move the internal pointer to the end of the array
77        end($array);
78        $key = key($array);
79        // By default, the pointer is on the first element
80        reset($array);
81        return $key;
82    }
83}
84