bluegray Posted May 31, 2010 Share Posted May 31, 2010 Hi Php freaks! =) I'm trying to build two functions that take an array's keys and values, and puts them into two strings. Here are the two functions respectively: function array2fieldtest ($data) { //var_dump($data) ; //$element_count = count ($data) ; foreach ($data as $ky) { $key = key ($data) ; $keys[] = $key ; next ($data) ; } $fields = 'id, ' . implode (', ', $keys) ; echo nl2br ("$fields\n") ; } and... function array2valuetest ($data) { //var_dump($data) ; //$element_count = count ($data) ; $results = '\"\", \"' . implode ('\", \"', $data). '\"' ; echo "<p>$results </p>" ; } Now, on the Echo of the functions, I get exactly what I intended as an output: "id, namefirst, namelast, social, solo, additional" " \"\", \"1\", \"2\", \"3\", \"\", \"End Here.\" " However, when I later invoke the functions and try to assign their results to a variable, the variable remains blank. Here's how I do it: $input = $_POST ['test'] ; $fields = array2fieldtest ($input) ; $values = array2valuetest ($input) ; echo "Hi we are [ $fields ]& [ $values ]" ; So the final output looks something like: "Hi we are [ ]& [ ]" when it should look like : "Hi we are [ id, namefirst, namelast, social, solo, additional ]& [ \"\", \"1\", \"2\", \"3\", \"\", \"End Here.\" ]" How can I correct this? Quote Link to comment https://forums.phpfreaks.com/topic/203392-custom-functions-refuse-to-be-assigned/ Share on other sites More sharing options...
jcbones Posted May 31, 2010 Share Posted May 31, 2010 Use "return" instead of "echo" function array2fieldtest ($data) { //var_dump($data) ; //$element_count = count ($data) ; foreach ($data as $ky) { $key = key ($data) ; $keys[] = $key ; next ($data) ; } $fields = 'id, ' . implode (', ', $keys) ; return nl2br ("$fields\n") ; } Quote Link to comment https://forums.phpfreaks.com/topic/203392-custom-functions-refuse-to-be-assigned/#findComment-1065522 Share on other sites More sharing options...
JD* Posted May 31, 2010 Share Posted May 31, 2010 You need to do a return in your function: function array2fieldtest ($data) { //var_dump($data) ; //$element_count = count ($data) ; foreach ($data as $ky) { $key = key ($data) ; $keys[] = $key ; next ($data) ; } $fields = 'id, ' . implode (', ', $keys) ; return nl2br ("$fields\n") ; } Quote Link to comment https://forums.phpfreaks.com/topic/203392-custom-functions-refuse-to-be-assigned/#findComment-1065524 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.