0

In my php code, i'm collecting all validation error messages into one array called $errors. Is it possible to echo all array elements like that: "1) Error 1 2) Error 2 ... " and so on?

2
  • 1
    Not really clear … You want to loop an array? Sure, PHP can do that … Commented Nov 10, 2011 at 20:25
  • What i wanna do is, to create new var $message and assign "1) Error 1 2) Error 2 ... " style message into it. Error messages will taken from $errors array Commented Nov 10, 2011 at 20:36

3 Answers 3

2

Your question is really unclear. Anyway if I understand your problem, this should work:

If you need all the messages in a single string use this:

$i = 1;
$message = '';
foreach($errors as $value)
{
   $message .= "$i) Error $value\n";
   $i++;
}

If you need to have them in a array, use this one instead:

$i = 1;
$message = array();
foreach($errors as $value)
{
   $message[] = "$i) Error $value";
   $i++;
}
Sign up to request clarification or add additional context in comments.

1 Comment

What i wanna do is, to create new var $message and assign "1) Error 1 2) Error 2 ... " style message into it. Error messages will taken from $errors array
1

The foreach construct is suited well for this:

foreach($errors as $key => $value) {
  printf('%s) %s', htmlspecialchars($key), htmlspecialchars($value));
}

I hope I understood your question, it's not really clear what you want to do

1 Comment

What i wanna do is, to create new var $message and assign "1) Error 1 2) Error 2 ... " style message into it. Error messages will taken from $errors array
0

The good ol' c style is totally valid php:

for ($i = 0; $i < count($error); $i++)
{
    echo "" . ($i+1) . ") " . $error[$i];
}

3 Comments

This will not work if the key are not numerical or numerical and not sequential.
What i wanna do is, to create new var and assign "1) Error 1 2) Error 2 ... " style message into it. what if i declare '$message=array();' before for loop then place message[]= instead of echo.?
so then, create a var $message = ""; and instead of the echo line above, do the following: $message .= ($i+1) . ") " . $error[$i] . "\n"; (assuming of course, that the keys in the array are numbers, as Aurelio De Rosa pointed out :)). This concatenates the current expression to what message already has in it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.