Convert Comma Separated String into Array

Easy way to turn a CSV file into a parseable array.

<?php
$str="foo,bar,baz,bat";
$arr=explode(",",$str);
// print_r($arr);
?>

Comments

  1. User Avatar
    Ariel
    Permalink to comment#

    Is there a way to take a comma separated string like say: Tags: Something, somethingelse, thirdsomething into

    Tags:
    Something
    Somethingelse
    thirdsomething

    Perhaps by wrapping this code Tags: Something, somethingelse, thirdsomething in some kind of div? Is this possible?

  2. User Avatar
    Gafur
    Permalink to comment#

    Thank you very much,

  3. User Avatar
    Lezioni
    Permalink to comment#

    Ok, but if i put the $arr in a cycle for example “for”…how can i kmow the lenght of that array?…the problem for me it’s that one…the cycle should print $arr[0],$arr[1],$arr[2],$arr[3] and then stop, how can i tell it the it has to stop on number three?

    • User Avatar
      paul
      Permalink to comment#

      Lezioni, you can always use a foreach loop rather than a for loop.
      On the other had if you really want to now the lenth of an array
      use the count statement.

      $length=count($my_array);

  4. User Avatar
    Marco
    Permalink to comment#

    Thanks a lot! Impressive simplicity!

  5. User Avatar
    Michael
    Permalink to comment#

    That won’t work for a lot of cases. Consider:

    Field 1, Field 1,”This is text, with a comma.”

    That string will be broken into 4 pieces when it should only be 3.

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-anchoricon-closeicon-emailicon-linkicon-logo-staricon-menuicon-nav-guideicon-searchicon-staricon-tag