Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_getcsv example

Tags:

php

csv

I want to parse a comma separated value string into an array. I want to try the str_getcsv() php function but I can't find any good examples on how to use it.

For example I have an input where users submit tags for programming languages (php, js, jquery, etc), like the "tags" input in stackoverflow when you submit a question.

How would I turn an input with example value="php, js, jquery" into an array using str_getcsv?

like image 634
CyberJunkie Avatar asked May 29 '11 17:05

CyberJunkie


2 Answers

Its true that the spec at http://us3.php.net/manual/en/function.str-getcsv.php doesn't include a standard example, but the user-submitted notes do a decent job of covering it. If this is a form input:

$val = $_POST['value'];
$data = str_getcsv($val);

$data is now an array with the values. Try it and see if you have any other issues.

like image 83
Femi Avatar answered Oct 04 '22 09:10

Femi


I think you should maybe look at explode for this task.

 $values  = "php, js, jquery";
 $items = explode(",", $values);

 // Would give you an array:
 echo $items[0];  // would be php
 echo $items[1];  // would be js
 echo $items[2];  // would be jquery

This would probably more efficient than str_getcsv();

Note that you would need to use trim() to remove possible whitespace befores and after item values.

UPDATE:

I hadn't seen str_getcsv before, but read this quote on the manpage that would make it seem a worthwhile candidate:

Why not use explode() instead of str_getcsv() to parse rows? Because explode() would not treat possible enclosured parts of string or escaped characters correctly.

like image 26
stefgosselin Avatar answered Oct 04 '22 10:10

stefgosselin