Include same block of code multiple times

Hi everyone,

I need to use the same block of code in multiple places on the same page. Can I assign the following code to a variable, or is a function more appropriate or perhaps heredoc? It is just to simplify things and reduce the possibility of errors.

Thank you very much!!!

if (isset($name)){
echo '&name='.$name.'';
}
elseif(isset($_GET['name'])) {
$getname = explode(',', $_GET['name']);
foreach ($getname as $key => $value) {
	      echo '&name='.$value.'';
}
}

You could put it in a function. Or, if the variables always have the same values in the page, you could put the code on top of the page, and store the result in a variable instead of echoing it out. And then, in the multiple places in the page, echo out the variable.

By the way, if this code creates a part of the query string, then the else doesn’t make much sense. a querystring containing &name=eric&name=john&name=paula would pass only one ‘name’ to the receiving script.

Hey Guido,

I inserted the above code into a function:

function myfunction() {
if (isset($name)){
echo '&name='.$name.'';
}
elseif(isset($_GET['name'])) {
$getname = explode(',', $_GET['name']);
foreach ($getname as $key => $value) {
          echo '&name='.$value.'';
}
}
}

and then used myfunction() to call the function but nothing happened.

And then, in the multiple places in the page, echo out the variable.

That works.

By the way, if this code creates a part of the query string, then the else doesn’t make much sense. a querystring containing &name=eric&name=john&name=paula would pass only one ‘name’ to the receiving script.

I’ll need to check that out.

Thank you for your help

Ciao

Instead of echo inside the function, try having it return a string. Then echo myfunction();

Try passing $name as a parameter to the function.

Hi Mittineague and John_Betong,

thank you for your input!

I assigned ‘&name=’.$name.‘’; to a variable which I echo out if it is set. The other techniques you recommended didn’t work but it doesn’t matter right now.