Here's the 3 best ways of doing this.
Method One:
$x = '+3';
echo "1+2$x";
Double Quotes (") allows you to just pass the variable directly inside it.
Method Two:
$x = '+3';
echo '1+2'.$x;
When you don't want to use double quotes for whatever reason go with this. The (.) simply means "Add" basically. So if you were to want to add something like, 1+2+3+4+5 and have your variable in the middle all you need to do is:
$x = '+3';
echo '1+2'.$x.'+4+5';
Method 3: (Adding a variable directly inside the called variable)
$x = '+3';
$y = '+4';
$z = '+5';
echo "1+2${"x".$y.$z}";
Output: 1+2+3+4+5
Here we are adding $y
and $z
to $x
using the "."
; The {}
prioritize's the work inside it before rendering the undefined
variable.
This personally is a very useful function for calling functions like:
//Add the Get request to a variable.
$x = $_GET['tool'];
//Edit: If you want this if to contain multiple $xresult's change the if's
//Conditon in the "()" to isset($get). Simple. Now just add $xresultprogram
//or whatever.
if($x == 'app') {
$xresultapp = 'User requested tool: App';
}
//Somewhere down far in HTML maybe...
echo ${"xresult".$x}; // so this outputs: $xresultapp's value
//Note: doing ${"xresult".$_GET['tool']} directly wont work.
//I believe this is because since some direct non-echo html was loaded
//before we got to this php section it cant load cause it has already
//Started loading client side HTML and JS.
This would output $xresultapp
's 'User requested tool: App' if the url query is: example.com?tool=app
. You can modify with an else statement to define what happens when some value other than 'app' is requested. Remember, everything is case-sensitive so if they request 'App' in capitals it won't output $xresultapp
.