Jump to content

Custom functions refuse to be assigned


bluegray

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/203392-custom-functions-refuse-to-be-assigned/
Share on other sites

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") ;
}

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") ;
}

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.