0

I am having trouble getting associative names of my $_errors array right.

$item1 = 'password';
$item2 = 'firstname';

$this->addError(array($item1 => 'required'))
$this->addError(array($item2 => 'required'))

private function addError($error) {
    $this->_errors[] = $error;
}

public function error($item) {
    return array_search($item, $this->_errors);
}

When I do a print_r() on $_errors I get:

Array
(
    [0] => Array
        (
            [password] => required
        )
    [1] => Array
        (
            [firstname] => required
        )
)

But I need it to be:

Array
(
    [password] => required
    [firstname] => required
)

So I can call 'password' like so $this->_errors['password'];

2 Answers 2

2

Simply change your functions accordingly:

private function addError($element, $error) {
    $this->_errors[$element] = $error;
}

$this->addError($item1, 'required');
$this->addError($item2, 'required');

Of course this scheme will not allow you to track multiple errors for the same element at the same time; if you need to do that you have to rethink your desired result.

Sign up to request clarification or add additional context in comments.

Comments

1

Use a list() construct to break the array into key-value pair and then subject it to your $this->errors[] array variable.

private function addError($error) {
    $this->_errors[] = $error;
}

to

private function addError($error) {
    list($a,$b) = each($error);    //<--------- Add the list() here
    $this->_errors[$a] = $b; //<--------- Map those variables to your array 
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.