Вот решение, использующее массив $errors
, в котором хранятся все ошибки, и строку $all
, которая содержит желаемый вывод.Чтобы проверить, поставьте var_dump( $all);
в конце скрипта.
$errors = array();
$all = '';
// Loop over the values 1 through 20
foreach( range( 1, 20) as $i)
{
// Create an array that stores all of the values for the current number
$values = array(
'a' . $i . 'height' => $_POST['a' . $i . 'height'],
'a' . $i . 'width' => $_POST['a' . $i . 'width'],
'a' . $i . 'length' => $_POST['a' . $i . 'length'],
'a' . $i . 'weight' => $_POST['a' . $i . 'weight']
);
// Make sure at least one submitted value is valid, if not, skip these entirely
if( count( array_filter( array_map( 'is_numeric', $values))))
{
// This basically checks if there's at least one numeric entry for the current $i
continue; // Skip
}
// Validate every value
foreach( $values as $key => $value)
{
if( empty( $value))
{
$errors[] = "Value $key is not set";
}
// You can add more validation in here, such as:
if( !is_numeric( $value))
{
$errors[] = "Value $key contains an invalid value '$value'";
}
}
// Join all of the values together to produce the desired output
$all .= implode( '|', $values) . "\n";
}
Чтобы правильно отформатировать ошибки, попробуйте что-то вроде этого:
// If there are errors
if( count( $errors) > 0)
{
echo '<div class="errors">';
// If there is only one, just print the only message
if( count( $errors) == 1)
{
echo $errors[0];
}
// Otherwise format them into an unordered list
else
{
echo '<ul>';
echo '<li>' . implode( '</li><li>', $errors) . '</li>';
echo '</ul>';
}
echo '</div>';
}