Search code examples
phpmysqlloopswhile-loopseparator

how to separate mysql cell in PHP by given symbol


Suppose that in MySQL I have a row called "favourite_websites". If there are more then 1, then they are separated by comma ( , ).

Example user 1 has "favourite_websites" set as "facebook.com"

Example user 2 has it set as "facebook.com,google.com"

Example user 3 has it set as "facebook.com, google.com"

What I need is to loop each user and then get each their website separately as

<a href='http://[website]'>[website]</a>

If there are more then 1 website in the cell then it should echo smt like this

<a href='http://[website]'>[website]</a>
<a href='http://[website]'>[website]</a>

Solution

  • Convert your string to array by using explode : documentation.

    Example :

    <?php
        $favourites = "facebook.com, google.com";
        $favourites_array = explode(',', $favourites);
        foreach($favourites as $website){
            $website = trim($website); //remove space characters
            echo '<a href="http://'.$website.'">'.$website.'</a>';
        }
    ?>