Skip to content
Advertisement

PHP array – explode some comma separated elements into new items

How can I take an array with individual strings but also comma separated strings and explode the comma separated items into individual items? For instance:

while(($row =  mysql_fetch_array($downloads_query))) {
        $product_array[] = $row['product']; 
    }

$product_array[] returns:

item 1: "10003"
item 2: "10016"
item 3: "10008, 10007, 10010"

How can I split item 3 into individual items 3, 4 and 5 so that $product_array returns:

item 1: "10003"
item 2: "10016"
item 3: "10008"
item 4: "10007"
item 5: "10010"

Advertisement

Answer

while(($row =  mysql_fetch_array($downloads_query))) {
        if(strpos($row['product'],',') > -1){
                $product_array += explode(',',$row['product']);
        } else {
                $product_array[] = $row['product']; 
        }
    }

Here is fast solution 🙂 if there is comma it will explode it before adding it into your array.

  • As other people notice myslq_ functions are deprecated .. Better use mysqli or PDO instead 🙂
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement