Validate different values in associative array

Submitted by dani3l - 5 years ago

If you have an array like: array( array('key' => 'value'), array('key' => 'anotherValue'), array('key' => 'sameValue'), array('key' => 'sameValue') ); and you want to make sure that you cant have 'key' with same value twice i was searching a native way to do it, but couldn't find one - so this is my solution:

Validator::extend('different_in_array', function($attribute, $value, $parameters)
{
    if (is_array($value) and isset($parameters[0]) and is_string($parameters[0]))
    {
        $_values = array();

        foreach($value as $key => $val)
        {
            if (!is_array($val) or !isset($val[$parameters[0]]) or !$val[$parameters[0]] or in_array($val[$parameters[0]], $_values)) return false;

            $_values[] = $val[$parameters[0]];
        }

        return true;
    }

    return false;
});
comments powered by Disqus