Home › Forums › General Issues › Comma-separated array values
I’m not advanced with PHP and am having problems setting up array values to display with comma-separation instead of list items as in the documentation.
This is what I have:
$values = get_field('fieldname');
	if($values)			
	{ foreach($values as $value)
		{
		echo  $value ;
		}
	}
I’ve tried explode but am having trouble getting it to work. Thanks for any assistance.

Can you provide a sample of the get_field('fieldname'); data? Here’s a quick debug snippet to see what the field holds:
echo '<pre>'.print_r(get_field('fieldname'), true).'</pre>';
If you already have a comma-separated value and want to convert it to an array, try this little snippet out:
$values = explode(',', get_field('fieldname'));
if( count($values)){
    foreach($values as $value){
        echo trim($value);
    }
}
This snippet should work with a text string that looks something like one,two, three four, five-, six and should output this: onetwothreefourfivesix.
However, I have a feeling that you already have an array as provided by get_field('fieldname'), so if that’s the case then you don’t need to explode at all, just loop with a foreach() and output with something like echo $value.', ';. A snippet like this might look like:
$values = get_field('fieldname');
if( count($values)){
    foreach($values as $k=>$value){
        if($k) echo ', ';
        echo $value;
    }
}
In this example, $k is a counter that lets us know what item number we are currently working with. During the first loop, $k will be 0 so no comma will be printed.
This worked great! This is what I used:
$values = get_field('myfieldname');
if( count($values)){
    foreach($values as $k=>$value){
        if($k) echo ', ';
        echo $value;
    }
}
				
The topic ‘Comma-separated array values’ is closed to new replies.
Welcome to the Advanced Custom Fields community forum.
Browse through ideas, snippets of code, questions and answers between fellow ACF users
Helping others is a great way to earn karma, gain badges and help ACF development!
We use cookies to offer you a better browsing experience, analyze site traffic and personalize content. Read about how we use cookies and how you can control them in our Privacy Policy. If you continue to use this site, you consent to our use of cookies.