Page 1 of 1

Array Value into a Variable

Posted: Wed Sep 10, 2003 2:42 pm
by theoph
I have an array called $select. The following script works just fine, however, I wanting to put the result into a variable instead of displaying it on a web page. How can i do this?

Code: Select all

<?php 
	$numbercount =count($select);
	for ($i=0; $i<$numbercount; $i++) {echo $select[$i]. ", ";}
?>
-Newbie Dave

Posted: Wed Sep 10, 2003 2:47 pm
by Unipus

Code: Select all

<?php

	foreach($select as $key => $val) {
		$$key = $val;
	}
?>
... will turn every element of an associative array named "select" into a variable based on its key name.

Posted: Wed Sep 10, 2003 2:55 pm
by Unipus
Oh, I see. I didn't really read your post, did I?

Okay:

Code: Select all

<?

   $numbercount =count($select); 
   for ($i=0; $i<$numbercount; $i++) {
$array_data .= $select[$i]. ", ";
?>
That will append whatever the value of $select[$i] is to the end of everything else in $array_data so far, and then loop back and do it again. It will leave an extra (and possibly unwanted) comma at the very end, but you could fix this with a simple if ($i == $numbercount) inside the loop.

Posted: Wed Sep 10, 2003 4:41 pm
by theoph
:D , I see that I need to have a concatenation tag after the variable.

Thanks much!

Posted: Wed Sep 10, 2003 8:29 pm
by m3rajk

Code: Select all

<?
foreach($select as $value){
  $array_data .= $value. ", ";
}
$array_data = substr($array_data,0,-1);
?>
Unipus : this variation of what you said does it all automatically, and seems to me to be more efficient, though i'm not positive there's an difference

Posted: Wed Sep 10, 2003 8:47 pm
by Unipus
Oh, yeah... that's a nice way to do it.

Posted: Thu Sep 11, 2003 3:24 am
by twigletmac
You could simplify the code to:

Code: Select all

$csv_string = implode(',', $select);
then you don't need to loop through the array or remove a comma at the end.

Mac

Posted: Thu Sep 11, 2003 1:59 pm
by m3rajk
i've never used implode, but that made me think, is it anything like join?

Posted: Thu Sep 11, 2003 2:25 pm
by JAM
Exactly the same thing, just different name (from C).