Search code examples
phparraysechoenumerate

Numerate and echo array keys in PHP


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?


Solution

  • 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++;
    }