fuelphp-storage / fuelphp

FuelPHP framework
http://fuelphp.com
MIT License
274 stars 57 forks source link

[new feature]check only have array key. #50

Closed ve3 closed 5 years ago

ve3 commented 10 years ago

I was extend this method in my code. It check that 2d array must only have these key.

    /**
     * The haveOnlyKey2D is method checks if haystack array passed is 2 dimension array and all key match to the needle. If there are another keys in haystack, it will return false.
     * 
     * @param mixed $needle The searched value. This can be string, integer, or array.
     * @param array $haystack The array to check.
     * @return boolean Only all key in haystack match needle will be return true.
     */
    public static function haveOnlyKey2D($needle, array $haystack)
    {
        // is haystack is multi dimension array?
        if (\Arr::is_multi($haystack)) {
            return false;
        }

        $number_not_in_needle = 0;

        foreach ($haystack as $key => $item) {
            if (is_array($needle)) {
                // needle is array.
                if (!in_array($key, $needle)) {
                    $number_not_in_needle++;
                }
            } else {
                // needle is NOT array.
                if ($needle != $key) {
                    $number_not_in_needle++;
                }
            }
        }

        if ($number_not_in_needle == 0) {
            return true;
        }

        // not in conditions above.
        return false;
    }

example:

$_GET['cid']; $_GET['page']; $_GET['filter'];
\Arr::haveOnlyKey2D(array('cid', 'page'), $_GET); // return false.
$_GET['cid']; $_GET['page'];
\Arr::haveOnlyKey2D(array('cid', 'page'), $_GET); // return true.
$_GET['cid'];
\Arr::haveOnlyKey2D(array('cid', 'page'), $_GET); // return true.
emlynwest commented 10 years ago

It would be better to use array_intersect/array_diff/array_keys to check if an array contains only the keys you need. I don't think a new method is needed for this in Arr at the time. (This is also the wrong repo. For v1 you want fuel/fuel and for v2 Arr you want fuelphp/common)