Support

Account

Home Forums General Issues Comma-separated array values

Solved

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&#039);
    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;
        }
    }
Viewing 4 posts - 1 through 4 (of 4 total)

The topic ‘Comma-separated array values’ is closed to new replies.