Jump to content

Array Issue - Format Data


james182

Recommended Posts

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

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'

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.