Jump to content

join texts of variables


lindm

Recommended Posts

got the following function I need help to complete:

function sign() {
$num = func_num_args(); 

		for( $i = 0; $i < $num; ++$i ) {
        if value of variable != '' merge to $total=xxxxx
    }

    return $total;
}

print sign('','hello ','how ','are you?);

 

The output should be: hello how are you?

In other words the variables with values should be joined together. Can't get the xxx of the functions working.

 

Link to comment
Share on other sites

To complicate things I need to add a html tag around each variable like:

 

<span>row['one']</span>

 

Not sure your suggestion works?

 

Why didn't you specify that in your original post? Would get your problem solved faster.

 

But mikesta707's code should work. If you don't want to wrap blank vars in span tags, you can loop through each argument:

 

<?php
function sign() {
$return = '';
foreach (func_get_args() as $arg) {
	if ($arg != '') {
		$return .= "<span>$arg</span>";
	}
}
return $return;
}
?>

Link to comment
Share on other sites

ahh man, now it can't be a 1 line function

function sign() {
$string = "";
foreach(func_get_args() as $args){
$string .= (str_len($args) > 0) ? "<span>".$args."</span>" : "";
}
return $string;
}

 

dam badbad, always beating me. Oh well, our solutions are exactly the same, but mines a little short  :P

Link to comment
Share on other sites

dam badbad, always beating me. Oh well, our solutions are exactly the same, but mines a little short  :P

Mine would be even shorter (great joke potential right here) by using the ternary operator as well. And of course it can be a one line function:

 

function sign() {$return = ''; foreach (func_get_args() as $arg) {$return .= ($arg != '') ? "<span>$arg</span>" : '';} return $return;}

LOL ;)

Link to comment
Share on other sites

Clever, although it complaints that func_get_args() can't be used as a function parameter :)

 

Use a newer version of PHP (5.3.0 or above) or move it out of the parameter:

 

function sign() {
return ($a = func_get_args()) ? vsprintf(str_repeat("<span>%s</span>", count($args = array_filter($a, "strlen"))), $args) : "";
}

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.