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
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'

?>

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.