-4

I need to insert

<?php if (isset($_GET["marke"])) { echo "?marke="; echo $_GET["marke"]; echo "&farbe=gelb"; } else { echo "?farbe=gelb"; } ?>

into a variable.

But of course

<?php
$var = if (isset($_GET["marke"])) { echo "?marke="; echo $_GET["marke"]; echo "&farbe=gelb"; } else { echo "?farbe=gelb"; }
?>

 <?php
echo $var;
?>

isn't working ^^ What would the right Code look like?

Eddy Unruh
  • 199
  • 3
  • 9

4 Answers4

1

You must initialize the var and concatenate the strings:

$var = "?";
if (isset($_GET["marke"])) {
    $var .= "marke=" . $_GET["marke"] . "&";
}
$var .= "farbe=gelb";

And then:

echo $var;
0

You don't need to use a function; just use the ternary operator.

$var = (isset($_GET["marke"])) ? "?marke=" . $_GET["marke"] . "&farbe=gelb" : "?farbe=gelb";
theftprevention
  • 5,083
  • 3
  • 18
  • 31
  • I don't see a function... but `echo` is not necessary when setting a variable. – showdev Sep 19 '13 at 19:17
  • The title of the question mentions "inserting a function in a variable." And I'm not echoing anything in this sample... – theftprevention Sep 19 '13 at 19:18
  • Oh, gotcha -- I see "function" in the title. You're suggesting that asking for a function is misguided. Regarding `echo`, I was referring to the OP's use of `echo`, not yours. – showdev Sep 19 '13 at 19:20
  • 1
    Not sure the title having "function" in it is relevant considering the overall understanding of the basic syntax. ie, they may not actually want function – James Sep 19 '13 at 19:23
0

If you're just trying to set data to a variable if GET is set, and if not set to something else, use this:

if (isset($_GET["marke"])) 
  {
    $var = "?marke=".$_GET['marke']."&farbe=gelb";
  }
else
  {
    $var = "?farbe=gelb";
  }

But remember to validate GET data before using it with mysql etc, to make sure it's what you allow.

James
  • 4,644
  • 5
  • 37
  • 48
-2

Assuming that you want to save the output into a variable, and then do something before outputting the variable again, you can do something like this:

<?php
$var = if (isset($_GET["marke"])) { echo "?marke="; echo $_GET["marke"]; echo "&farbe=gelb"; } else { echo "?farbe=gelb"; 

echo <<<_END
<html>
//write something here
</html>
_END;

echo $var;
?>

Hope that helps!

Zhia Chong
  • 346
  • 2
  • 12