Add key and value (as argument via function) to array

58 Views Asked by At

First we have a property which is the array:

    private static $_errors = array();

An error can be added by sending it to a function, which will add it to the array:

    public function addError($error){
    self::$_errors[] = $error;
}

In any function, I can easily add an error as a string like this:

if(strlen($value) < $rule_value){
                            $this->addError("More than {$rule_value} characters are needed as {$item}.");
                        }

But I want to add a key and value, for example "message" => "hello", but I don't know how to do it. This:

if(strlen($value) < $rule_value){
                            $this->addError(['min_notmet'] = "More than {$rule_value} characters are needed as {$item}.");
                        }    

does not work. I tried various things. But it has to be one and the same array, I don't want to add the errors as separate arrays inside the array. Hope you can solve this!

1

There are 1 best solutions below

1
On BEST ANSWER

Modify your addError function:

public function addError($error, $key=false){
    if($key){
        self::$_errors[$key] = $error;
    }else{
        self::$_errors[] = $error;
    }

} 

Then it will go like this:

if(strlen($value) < $rule_value){
    $this->addError("More than {$rule_value} characters are needed as {$item}.", 'min_notmet');
}

If you don't provide $key parameter, it will just add the element as before, with numeric key.