Search code examples
phparrayswordpressfor-loopcycle

for cycle - page stops loading, any alternatives?


I need to echo array, but the page stops loading. I am running Wordpress.

    if($categories)  {
        for ($i=0;$i<count($categories);$i++) {
        echo $categories[$i].", ";
        }
    }

I really does not know why. Is there any other way to do that? Or grab array into one string. E.g.

$categories[0] = "aaa";
$categories[1] = "bbb";
$string = "aaa, bbb";

(Array have unknown number of values)


Solution

  • This is perfect for implode(), just use it like this:

    echo implode(", ", $categories);
    

    As an example:

    $categories = array("aaa", "bbb", "ccc");
    echo implode(", ", $categories);
    

    Output:

    aaa, bbb, ccc