Format validationsErrors

Written by James McDonald

December 5, 2019

A recursive function that takes a validation error array and return a string with all the different errors concatenated into a formatted string

Further to my previous posting

This function will walk the validationErrors array and return the error messages.

function formatValidationErrors($validationErrors = [], $errorMessage = null)
    // get Validation errors and append them into a string

    foreach ($validationErrors as $key => $value) {
        if (is_array($value)) {
            $errorMessage = formatValidationErrors($value, $errorMessage);
        } else {
            if ($errorMessage) {
                $errorMessage .= sprintf(". <strong>%s: </strong>", $value);
            } else {
                $errorMessage = sprintf("<strong>%s</strong>", $value);

    return $errorMessage;

Calling the code from your controller

// app/Controller/CartonController.php
$errorText = $this->Carton->formatValidationErrors($this->Carton->validationErrors);


Submit a Comment

Your email address will not be published.

You May Also Like…


Zebra Printer Language The above website has a page where you can enter ZPL and it...

PHP Iterators

Just came across a Youtube talk "Iterators in PHP" by Jake Smith published in 2014 that steps through the many...

PHP array_map Multiple Arrays

array_map can take multiple arrays. I like how it starts mapping through them starting at the first element of each...