What does the ${$} construct mean? [duplicate] - php

This question already has answers here:
In PHP, what does the ${$ } syntax do?
(3 answers)
Closed 9 years ago.
I am new to PHP so please i am sorry if this question is a noob. I don't know its name so couldn't find it. I read it in this piece of code. What does it mean?
Line 5: ${$key}
<?php
$expected = array( 'carModel', 'year', 'bodyStyle' );
foreach( $expected AS $key ) {
if ( !empty( $_POST[ $key ] ) ) {
${$key} = $_POST[ $key ];
} else {
${$key} = NULL;
}
}
?>

This is the same as $$key and means a var named $key
i.e.
$test = "foo";
is the same as
$a = "test";
$$a = "foo";

It's a variable variable. Please read more here: http://php.net/manual/en/language.variables.variable.php

The notation ${$key} is an alternative writing style to simply $$key which is used for variable variables.
One particular case in which you could use that notation is when you do tricks like this:
$var = 'foo_x';
$key = 'x';
${'foo_' . $x} = 'hello';
echo $foo_x; // hello

Set variable with name $key.
$var = NULL;
$name = 'var';
${$name} = TRUE;
var_dump($var); // TRUE
As well as:
$$name = TRUE;

It is a way to use dynmaic variable names. See here: http://php.net/manual/en/language.variables.variable.php

It allows for the use of complex expressions.
It's called complex (curly) syntax, you can find more information at http://php.net/manual/en/language.types.string.php#language.types.string.parsing.complex

Related

what is the meaning of ${$key} in the code below? [duplicate]

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 6 years ago.
I just need to know what is the meaning of ${$key} in the code. I already searched google but didn't find answers for this code. So please help me understand it ?
<?php
foreach ($_POST as $key => $value) {
$temp = is_array($value) ? $value : trim($value);
if (empty($temp) && in_array($key, $required)) {
$missing[] = $key;
${$key} = '';
} elseif (in_array($key, $expected)) {
${$key} = $temp;
}
}
?>
Let's say, we have given code:
<?php
$a = 'Hello';
$key = 'a';
echo ${$key};
?>
will print:
Hello
What you are doing here is referring to the value which name is stored in another variable.
Using ${} is a way to create dynamic variables, example:
${'a' . 'b'} = 'hello world!';
echo $ab; // hello world!
Read more at official documentation.

declaring a big list of variables [duplicate]

This question already has answers here:
Using braces with dynamic variable names in PHP
(9 answers)
Closed 9 years ago.
I have a big list of variables:
$variable_1 = $_POST['variable_1'];
$variable_2 = $_POST['variable_2'];
$variable_3 = $_POST['variable_3'];
$variable_4 = $_POST['variable_4'];
...
..
.
$variable_86 = $_POST['variable_86'];
What would be the best way to declare all of these variables? Should I just declare them all like above, should I put them in an array, can I declare using a loop?
for ($i = 0; $i <= 86; $i++){
if (isset($_POST["variable_$i"]))
${'variable'.$i} = $_POST["variable_$i"];
}
See this question to learn about Dynamic Variable names.
EDIT: Added the isset command. isset() checks whether a variable is already declared or not
You can use any of the following:
foreach($var as $key=>$value) {
echo $value;
}
and/or:
foreach($_POST['var'] as $key=>$value) {
echo $value;
You could use this also, that will iterate through all POST values:
foreach($_POST as $key=>$value) {
echo "$key=$value";
}
Also, assuming $_POST['variable_1'] $_POST['variable_2'] etc.
foreach($_POST as $k => $v) {
if(strpos($k, 'variable_') === 0) {
echo "$k = $v";
}
}

PHP what does it mean when using this '$$var'? [duplicate]

This question already has answers here:
Reference Guide: What does this symbol mean in PHP? (PHP Syntax)
(24 answers)
Closed 9 years ago.
I am trying to learn php, and I saw this in a foreach loop what does it mean?
I understand &$var which its a direct reference to the memory address of the object.
But what does $$var means? what is it exactly?
This is the example.
foreach($this->vars as $key => $value)
{
$$key = $value;
echo "$$Key: " . $$key;
echo "Key: " . $key;
echo "<br/>";
echo "Value: " . $value;
}
You're looking at a variable variable. e.g.
// original variable named 'foo'
$foo = "bar";
// reference $foo dynamically by evaluating $x
$x = "foo";
echo $$x; // "bar";
echo ${$x}; // "bar" as well but the {} allows you to perform concatenation
// different version of {} to show a more "complex" operation
$y = "fo";
$z = "o";
echo ${$y . $z}; // "bar" also ("fo" . "o" = "foo")
To show an example more closely matching your question:
$foo = "foo";
$bar = "bar";
$baz = "baz";
$ary = array('foo' => 'FOO','bar' => 'BAR','baz' => 'BAZ');
foreach ($ary as $key => $value){
$$key = $value;
}
// end result is:
// $foo = "FOO";
// $bar = "BAR";
// $baz = "BAZ";
It's a variable with the name $key. For example,
If $k='somevar', then $$k = $somevar.
Variable variable. The var name is what is contained in $var.
If $key = 'test' then $$key will be evaluate to a var named $test.
Also, there are very few practical uses. Most often arrays would be better.

Assigning values to a large number of variables in php after an if ()

Do you know a better way to do thing when it comes to assigning values to a large number of variables after an if?
In my case it like this:
$akeType = array_key_exists('type',$handle);
$akeParent = array_key_exists('parent',$handle);
$akeUserName = array_key_exists('userName',$handle);
$akeUserId = array_key_exists('userId',$handle);
$akeCountryCode = array_key_exists('userId',$handle);
if ( $akeType && $akeParent && $akeUserName && $akeUserId & $akeCountryCode ) {
$listType = $handle['type'];
$listParent = $handle['parent'];
$listUserName = $handle['userName'];
$listUserId = $handle['userId'];
$foo = $_POST['foo'];
$bar = $_POST['bar'];
$listCountryCode = $handle['countryCode']; // Is there a way to clean up this part? The assignments to variables.
take a look at the extract -- Import variables into the current symbol table from an array
extract($handle, EXTR_OVERWRITE, "ake_");
You can do this with the somewhat more obscure code following:
$keys= array('type','parent','userName', 'userId');
foreach($keys as $key) {
$nametoset= "list".ucfirst($key);
$$nametoset= $handle[$key];
}
$$nametoset refers to the variable named like the string $nametoset.
Similar code may be used for the $ake... variables.
You can use Variable variables to set your variable list.
For your specific case, you can use the following code:
foreach ($handle as $key => $value) {
$var_name = 'list'.$key;
$$var_name = $value;
}
foreach ($_POST as $pkey => $pvalue) {
$$pkey = $pvalue;
}
These loops create variables depending on your arrays keys.

Can a PHP variable know its name? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
How to get a variable name as a string in PHP?
Example:
Can something like this be achieved in PHP?
$Age = 43;
output_variable_name_and_value($Age);
/*
outputs:
"The requested variable name is Age and its current value is 43";
*/
//If possible, how would the line marked below with ? ? ? ? be?
function output__variable_name_and_value($input)
{
$var_name = get_name_somehow($input); // ? ? ? ?
echo "The requested variable name is {$var_name}
and its current value is {$input}";
}
This is not possible, easily. You have to use $GLOBALS;
function get_variable_name($var) {
foreach($GLOBALS as $k => $v) {
if ($v === $var) {
return $k;
}
}
return false;
}
The only downfall is, it may return a different variable name if they both have the same value.
Or this,
function varName( $v ) {
$trace = debug_backtrace();
$vLine = file( __FILE__ );
$fLine = $vLine[ $trace[0]['line'] - 1 ];
preg_match( "#\\$(\w+)#", $fLine, $match );
print_r( $match );
}
which I found here: How to get a variable name as a string in PHP?
You can use this function:
function var_name(&$iVar, &$aDefinedVars) {
foreach ($aDefinedVars as $k=>$v)
$aDefinedVars_0[$k] = $v;
$iVarSave = $iVar;
$iVar =!$iVar;
$aDiffKeys = array_keys (array_diff_assoc ($aDefinedVars_0, $aDefinedVars));
$iVar = $iVarSave;
return $aDiffKeys[0];
}
Call it like this:
var_name($Age, get_defined_vars());
Source: http://mach13.com/how-to-get-a-variable-name-as-a-string-in-php
Well..
You can figure out what called the output__variable_name_and_value function using debug_backtrace.
Then you know a filename and line number, so you could try to parse the sourcefile and figure out whats between output__variable_name_and_value( and ).
Probably a bad idea though!

Categories