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

Link to comment
Share on other sites

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

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.