I'm new to PHP so please forgive me if this is a stupid question.
How do you include a variable in a variable?
What I mean is:
<?php
$variable_a = 'Adam';
$variable_b = '$variable_a';
?>
In other words the second variable is the same as the first one.
I won't bother explaining why I need to do it (it will confuse you!), but I just want to know firstly if it's possible, and secondly how to do it, because I know that code there doesn't work.
Cheers,
Adam.
Don't use the quotes, they indicate a string. Just point to the variable directly, like this:
$variable_b = $variable_a;
If you want the variables to be equal, use:
$variable_b = $variable_a;
If you want the second variable to contain the first, use variable parsing:
$variable_b = "my other variable is: $variable_a";
Or concatenation:
$variable_b = 'my other variable is: ' . $variable_a;
PHP have this advantage in producing one string variable's value based on another. To do this, write code like this:
$b = "My name is $name.";
The following code does NOT work:
$b = '$name';
Other occasions in which coding like this works are:
$b = <<<STRING
Hello, my name is $name...
STRING;
If you want to access an array, use:
$b = "My ID is {$id['John Smith']}.";
and of course,
$b = <<<STRING
Hello, my name is {$username}, my ID is {$id['John Smith']}.
STRING;
I recommend using {} because I frequently use Chinese charset in which occasion coding like
$b = "我是$age了。";
will cause PHP look up for variable $age了。 and cause error.
Either without quotes to reference the variable directly, since quotations means it's a string
$variable_b = $variable_a;
Or you can ommit the variable in double quotations, if you want it to appear in a string.
$variable_b = "My name is $variable_a";
Related
I'm trying to modify the name of the key dynamically based on which rows are being fetched, but my syntax seems to be slightly off within the query. After moving the quotes around more times than I care to admit, I finally decided it was time to ask for help ;-)
$var = '$foo_row';
$MAX_5A = ${$var . '["MAX_5A"]'};
Instead of
$MAX_5A = $foo_row['MAX_5A'];
Bonus points if someone wants to explain to me the logic behind the correct syntax :-)
This should work for you:
(Just use variable variables with curly quotes to make sure PHP doesn't think this: ${$var["MAX_5A"]}. Also note I removed the dollar sign in the string)
$var = 'foo_row';
//^ dollar sign removed
$MAX_5A = ${$var}["MAX_5A"];
$var = 'foo';
$bar = 'var';
echo $$bar; // foo
Logic: A variable variable takes the value of a variable and treats that as the name of a variable.
Can I do something like this?
$captcha_results = $_REQUEST[$_REQUEST['field_name']];
I am interested in it, because I try to find out where I've made a mistake.
Thank you in advance.
Yes, of course. The one you've just asked is one of variable variables. You can learn more the PHP variables here:
PHP Variable Basics
Variable in Variable
For example, you have $var containing value of foobar. You can use the value for other references (in my case, as an index of an array), as shown below.
$var = 'foobar';
$array['foobar'] = 'bar';
echo $array[$var];
This will output bar as a result.
I have a very simple question. But is really making me crazy.
I have a statement say:
example and example with one php variable like $loggedin_user_name
First of all, I want to store the above sentence in MySQL database and then take it back whenever I want to print the above statement. It seems that their is no issue.
But when I tried to print data after extracting from database it is printing the same statement. But i guess, it has to print the logged in user name instead of $loggedin_user_name in the above statement.
So, is it possible to print the variable within the variable? If yes, please suggest a way.
use sprintf()
$str = "example and example with one php variable like %s";
Then load it from database and fill
$out = sprintf($str, $loggedin_user_name);
If it is always the same variable name, I would suggest using
echo str_replace($fromDb, '$variableToReplace', $variableToReplace);
You can use preg_match to find you variable name in string and then replace it with str_replace.
$name = "ABC";
$bla = "$name";
echo $bla; //ABC
Will always be "ABC", because PHP is evaluating your variable when asigning to $bla.
You can use single-quotes to avoid that behaviour (like $bla='$name'; //$name) or you quote the $-sign (like $bla="\$name"; //$name). Then you can store your string like you wanted into your database.
But you can not (only when using eval(), wich you MUST NOT DO in good PHP-Code) build this behaviour, that php has, when printing fulltext.
Like Mentioned in another answer, you should use printf or sprintf and replace the $loggedin_user_name with %s (for "string).
Best would be to concatinate a string:
$exampleWithUsername = 'example' . $loggedin_user_name;
echo $exampleWithUsername;
'example' is a hardcoded string, but you can give it a variable containing string $example, or directly concatinate $username into $example.
You can use eval function, it can be used like your example:
$loggedin_user_name = 'bilal';
$str = "example and example with one php variable like $loggedin_user_name";
eval("\$str = \"$str\";");
echo $str;
Cons:
If your str variable or string/code which you give to eval as a parameter is filled by users, this usage creates a vulnerability.
In case of a fatal error in the evaluated code, the whole script exits.
Already asked but question was closed so here it is again:
I need to understand the code that renames values.
For example, I have $name which outputs 'A Long Way From Home', in case the script encounter this value I need to rename the value to 'LongWay34' into $name2 so I can use it somewhere else.
There's no need for any uber-script, I have just a few elements I need to modify and I can write a line for each one!
I hope I've been clear, thanks in advance for the help!
k
if($name === 'A Long Way From Home') $name2 = 'LongWay34';
...?
There is no such thing like rename in PHP.
There are variables, and you can assign a value to them.
Variables can hold data. To put data into variable you assign something to it. Examples:
$variable1 = "text value";
$variable2 = 24; //number value
$variable3 = $othervariable; // assign value of one variable to another (like "copy")
You can't rename variable. You can create new variable with diffrent name and assign old variable value to the new one.
$new_variable = $old_variable;
If I understand you correctly - you want code, that will run when variable value will become "some value". Normal variable don't have any "trigger" features, that will trigger some code. You have to check value of that variable and make conditional blocks (if for example).
There are special "variable" types, that can monitor changes of variable, run some additional code when variables are accessed. They are called classes, but now this may be too complicated for you to understand.
This is annoying me. In theory it should be easy but I don't live in theory.
Basically, I have an option to set a custom algorithm to make a 'code' that is either string or int.
This is user generated, and I then call that.
I have attempted to execute it using this code:
$code = eval('return($custalg);');
but that returns the actual algorithm entered, and not the value it would produce.
So my question is, how would I manage to execute the string in $custalg as php and then save the result into a variable?
It looks you are not aware of difference between single quoted ' and double quoted " strings in PHP. You should use:
$code = eval("return($custalg);");
if you want $custalog to be expanded:
The most important feature of double-quoted strings is the fact that
variable names will be expanded. See string parsing for details.
See more in docs.
So basically correct syntax depends on what $custalg is and where it is assigned. In your case I guess your $custalg is assigned in main code so you do not want substitution. Use code like this then:
$code = eval("return \$custalg;");
You can get an echoed output with using the PHP output control functions:
ob_start();
eval("echo $custalg;");
$tmp = ob_get_contents();
ob_end_clean();
$evalOutput = $tmp;
Or you just assign the return value to a global variable.