Avatar of peter-cooper
peter-cooper

asked on 

Convert php array to comma seperated list

Hi
I have an array that I need to convert to comma seperated for inclusion in mysql. I have posted my code and would appreciate any help or guidance. Thanks

output:

[boxdest] => Array
        (
            [0] => WD1
            [1] => WD10
            [2] => WD11
        )

Open in new window


php

<?php
	        $conn = mysql_connect("localhost","root","");
		mysql_select_db("sample",$conn); 
		$result = mysql_query("SELECT * FROM boxes where department = '{$_GET['dept']}' ORDER BY custref ASC");
?>
								
		<select name="boxdest[]" id="boxdest" size="7" multiple="multiple">

<?php
		$i=0;
		while($row = mysql_fetch_array($result)) {
?>
		<option value="<?php echo $row["custref"];?>"><?php echo $row["custref"];?></option>
<?php
		$i++;
		}
?>
		</select>

<input type="button" id="submit2" name="submit2" value=">" />
<input type="button" id="submit3" name="submit3" value="<" />
<select name="boxdest2[]" id="boxdest2" size="7"  multiple="multiple"></select>

<script type="text/javascript">
	
  $('#submit2').click(function () {
  var selected = $('#boxdest > option:selected');
  $('#boxdest2').append(selected.clone());
  selected.hide();
});

   $('#submit3').click(function () {
   $('#boxdest').append($('#boxdest2 > option').clone());
   $('#boxdest2').empty();
});
</script>

Open in new window


results page
This is what I have tried in results page

if (isset($_POST['boxdest'])) 
	{
 
        if (!empty($_POST['boxdest'])) 
		{
 								
                $destroydata = split(',', $_POST['boxdest'][0]);
 		$result = array();
                
                                                                
                foreach ($destroydata as $val4)
                {
			if ( $val4 != "" )
                        {
                                
                                  $boxdest[] = $val4;
				  $result[] = $boxdest;
				    
                        }
              }
      }

Open in new window

PHP

Avatar of undefined
Last Comment
peter-cooper
ASKER CERTIFIED SOLUTION
Avatar of Banshi lal dangi
Banshi lal dangi
Flag of India image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of peter-cooper
peter-cooper

ASKER

Thanks for reply. Do i still need to run this through foreach loop or just use $str in mysql query.
It will convert the given array into the comma separated string, as like below.
$arr = array ( 0 => "lorem",1 => "ipsum", 2 => "dolor");

$str = implode (", ", $arr);

echo $str; //it will output result  - 'lorem, ipsum, dolor'

Open in new window


And if you want again to convert comma separated string into the Array you can achieve that as follows.
$str = "lorem, ipsum, dolor";
$arr= explode(", ",$str);
print_r (explode(", ",$arr)); //it will ouput result as - Array ( [0] => lorem[1] => ipsum [2] =>dolor )

Open in new window

Avatar of peter-cooper
peter-cooper

ASKER

Thanks Banshi. There is one problem. I am trying to count the number of items in the array and it only shows one not 3. Do i need to run the $str through foreach loop to count the items. Thanks
If you want to count the number of item in an array, you can use the Count() method.
$arr = array ( 0 => "lorem",1 => "ipsum", 2 => "dolor");
$total = count($arr); 
echo $total; //it will output 3

Open in new window

Avatar of peter-cooper
peter-cooper

ASKER

So in my case would that be like the following fro your code example. thanks

$total = count($str); 

Open in new window

Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

More on implode here

$total = count($str);

Open in new window

Won't work - $str is now a string - so the result will be $total = 1

Here is an extension to Banshi's solution - which is the right one
$data = is_array($__POST['boxdest']) ? $__POST['boxdest'] : array();

// The above guarantees that $data is set AND is an array. If the $_POST['boxdest'] 
// does not exist it fails over to an empty array
// Now we can simply do this

$str = implode(',', $data);
$total = count($data);

Open in new window

Avatar of peter-cooper
peter-cooper

ASKER

Thanks for that Julian. Shall I start a new question for the count because Banshi answered my original question. thanks
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

What do you still need with the count - I thought that was solved in my last post.

count on the $data array (extracted from $_POST) will give you the number of items in the original array.
$str contains the converted array - you should have everything you need.
SOLUTION
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
Avatar of Ray Paseur
Ray Paseur
Flag of United States of America image

Some good learning resources for PHP are available here:
https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html
Avatar of peter-cooper
peter-cooper

ASKER

Julian. To award you answer for the count question.
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

To award you answer for the count question.
When you assign points you can choose more than one answer - you chose the one that best answers your question as "Best Solution" and any others become "Assisted Solutions". You can choose in the wizard how to apportion points.

This is the standard practice at EE - we don't open new questions just for the purpose of assigning points.
Avatar of peter-cooper
peter-cooper

ASKER

I only joined today after being away from EE for some time. Totally different from when I used it. If you want to bring to attention of moderator, I will be only too willing to awatd points again. Thanks
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

I only joined today after being away from EE for some time.
Welcome back - yes they have made quite a few changes.

I have re-opened the question for you to regrade
Avatar of peter-cooper
peter-cooper

ASKER

Thanks for your help.
Avatar of Julian Hansen
Julian Hansen
Flag of South Africa image

You are welcome.
Avatar of peter-cooper
peter-cooper

ASKER

Julian. I have got it working. One think, initially i have the submit disabled so users cannot submit an empty list. Is there way with your code to detect if a list has items and do something like the code below. However if there are items then make it false. Thanks

$("#submit").prop( "disabled", true);

Open in new window

Avatar of peter-cooper
peter-cooper

ASKER

Julian. Sorry. Didn't mean to post that here. Thanks
PHP
PHP

PHP is a widely-used server-side scripting language especially suited for web development, powering tens of millions of sites from Facebook to personal WordPress blogs. PHP is often paired with the MySQL relational database, but includes support for most other mainstream databases. By utilizing different Server APIs, PHP can work on many different web servers as a server-side scripting language.

125K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo