2
\$\begingroup\$

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.

\$\endgroup\$
2
  • 1
    \$\begingroup\$ No way to use less foreach loop and get it cleaner. \$\endgroup\$ – Shoe Dec 14 '11 at 17:32
  • 1
    \$\begingroup\$ It is impossible to tell without knowing the exact structure of $errors. \$\endgroup\$ – Paul Dec 15 '11 at 0:56
5
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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' :)

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

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.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.