james182 Posted June 22, 2012 Share Posted June 22, 2012 i am trying to get this to format the data properly. I want it to format like this 'D',E','F','G','H' But this is what i get: "D"E","F","G","H","I",J" "", $colour = "D-E-F-G-H-I-J-"; // string to be formatted. $colours = explode('-', $colour); $num_items = count($colours); $colour_is = ''; $i = 0; foreach ($colours as $key => $value) { if ($i == 0) { // first $colour_is .= ' "'. $value; } else if ($i == $num_items - 1) { // last $colour_is .= $value. '" '; }else{ $colour_is .= '"'. $value .'",'; } $i++; } print_r($num_items .' - '. $colour_is); Help on this would be nice. Thanks. Link to comment https://forums.phpfreaks.com/topic/264594-array-issue-format-data/ Share on other sites More sharing options...
xyph Posted June 22, 2012 Share Posted June 22, 2012 <?php $colour = "D-E-F-G-H-I-J-"; // string to be formatted. $colours = explode('-', $colour); $colours = array_slice($colours, 0, 5); print_r($colours); ?> Link to comment https://forums.phpfreaks.com/topic/264594-array-issue-format-data/#findComment-1356032 Share on other sites More sharing options...
Psycho Posted June 22, 2012 Share Posted June 22, 2012 I think he wants the output to be a string with each letter in single quotes and separated by commas. <?php $colour = "D-E-F-G-H-I-J-"; // string to be formatted. //Explode into array, array_filter() will remove the empty value at the end $colours = array_filter(explode('-', $colour)); //Put single quotes around each element foreach($colours as &$value) { $value = "'{$value}'"; } //Output the values, separated by commas echo implode(',', $colours); // OUTPUT: 'D','E','F','G','H','I','J' ?> Link to comment https://forums.phpfreaks.com/topic/264594-array-issue-format-data/#findComment-1356043 Share on other sites More sharing options...
.josh Posted June 22, 2012 Share Posted June 22, 2012 skip the foreach.. $colour = "D-E-F-G-H-I-J-"; $colours = array_filter(explode('-', $colour)); echo "'" . implode("','", $colours) . "'"; Link to comment https://forums.phpfreaks.com/topic/264594-array-issue-format-data/#findComment-1356044 Share on other sites More sharing options...
james182 Posted June 22, 2012 Author Share Posted June 22, 2012 Thanks for that. Link to comment https://forums.phpfreaks.com/topic/264594-array-issue-format-data/#findComment-1356064 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.