Last Updated: February 25, 2016
· idered

[PHP] Use implode instead of a loop

Previously to echo elements of an array I've used a loop:

echo '<div class="errors">';

foreach($errors as $error) {
    echo '<p>' . $error . '</p>';

echo '</div>';

But lately I've learned this technique:

echo '<div class="errors"><p>' . implode('</p><p>', $errors) . '</p></div>';

It does the same but looks better(at least for me).

2 Responses
Add your response

Thanks this helped me a lot ^_^

over 1 year ago ·

Hi, I'm using both methods, but I am wondering if one of those methods is faster?
I think, that calling an external function "implode" have to be much more slower, because PHP interpretter have to make some memory allocations for function parameters and returned values. Have you some info about this?

Thx ;)

over 1 year ago ·