William William - 3 months ago 8
PHP Question

Why do I get the error 'Illegal offset type' in this code?

Why do I get the error 'Illegal offset type' in this code on the line

$errors[$field] .= '<div class="error"><p>' . $error . '</p></div>';
?

Code:

$errors = [];
foreach ($validation->errors() as $field)
{
$errors[$field] = '';
foreach ($field as $error) {
$errors[$field] .= '<div class="error"><p>' . $error . '</p></div>';
}
}


Validation:

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

public function errors()
{
return $this->errors;
}


Solution:

foreach ($validation->errors() as $key => $fieldErrors)
{
$errors[$key] = '';
foreach ($fieldErrors as $error) {
$errors[$key] .= '<div class="error"><p>' . $error . '</p></div>';
}
}

Answer
foreach ($field as $error)

this line suggests that $field is an array. You cannot use an array as the key to another array.

$errors[$field]  << won't work!

To fix, change your addError method to:

private function addError($field, $error)
{
   $this->errors[$field] .= $error; //I changed [$field][] to [$field]
}
Comments