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?
-
1Not really clear … You want to loop an array? Sure, PHP can do that …knittl– knittl2011-11-10 20:25:56 +00:00Commented 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 arrayheron– heron2011-11-10 20:36:16 +00:00Commented Nov 10, 2011 at 20:36
Add a comment
|
3 Answers
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++;
}
1 Comment
heron
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 arrayThe 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
heron
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
The good ol' c style is totally valid php:
for ($i = 0; $i < count($error); $i++)
{
echo "" . ($i+1) . ") " . $error[$i];
}
3 Comments
Aurelio De Rosa
This will not work if the key are not numerical or numerical and not sequential.
heron
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.?djhaskin987
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.