Collecting form errors to be displayed

I have a piece of code that get errors from form and display to view:

$errors =$form->getMessages();
$msg = ''; foreach ($errors as $error) { foreach ($error as $err) {$msg .= $err . '<br/>'; } }$this->view->error_message = $msg;  It look so ugly, but now I don't have any ideas to improve it. Thank for help. • No way to use less foreach loop and get it cleaner. – Shoe Dec 14 '11 at 17:32 • It is impossible to tell without knowing the exact structure of$errors. – Paul Dec 15 '11 at 0:56

You can use array_merge to reduce the array from 2-dim to 1-dim, then implode the array.

$this->view->error_message = implode(array_reduce($form->getMessages(),
"array_merge",
array()),
"<br/>");


http://php.net/manual/en/function.array-merge.php

http://www.php.net/manual/en/function.array-reduce.php

Im assuming your $errors array looks like this: $errors = array(array('message 1'), array('message 2'), array('message 3'));


Then you could use something like this:

$msg = ''; foreach($errors as $inner) {$msg .= current($inner) . '<br />'; } echo$msg;
// message 1<br />message 2<br />message 3<br />


I dont know if its more efficient than the 2 foreach loops though.

On the other hand I personally would look into modifying the getMessages() mehtod so that it returns a single array and not a multidimensional one. With a single array you just need to implode it with a 'br' :)

• by using current() it not get all $error in$errors :( – hungneox Dec 14 '11 at 15:43

Given errors like this:

$errors = array(array('message 1a','message 1b'), array('message 2'), array('message 3'));  I you could make a function that can call itself to account for the nested arrays. function showErrors($errors) {
foreach ($errors as$error) {
$msg .= (is_array($error))? showErrors($error) :$error.'<br/>';
}
return($msg); }$msg = showErrors(\$errors);


Not sure it's cleaner, but it may be more versatile. This will accommodate deeper nested arrays should the need arise. If possible, I like Pratt's suggestion of supplying a single array.