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

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.

Related

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.

How do I get all values of a foreach into a PHP variable? [duplicate]

This question already has answers here:
Multidimensional Array PHP Implode [duplicate]
(5 answers)
Closed 8 years ago.
foreach ($tests as $test) {
$var = $test['somekey'];
}
echo $var;
How do I get all values of a foreach into a php variable? It seems to be picking up only the last variable.
you're overwriting $var on each iteration. with a dot as follows, this will append instead of overwrite.
$var .= $test['somekey'];
How about:
$data = array() ;
foreach ($tests as $test) {
$data[] = $test['somekey'];
}
echo implode(" ; ", $data) ;
The answer you're looking for depends on what you wish to do.
If you wish for an array, use:
$var = array();
foreach ($tests as $test) {
$var[] = $test['somekey'];
}
print_r($var);
or if you have PHP version >= 5.5.0 you can use:
$var = array_column($tests, $test);
If you wish for a string, use:
$var = "";
foreach ($tests as $test) {
$var .= $test['somekey'];
}
print_r($var);
If you wish for a number, use:
$var = 0;
foreach ($tests as $test) {
$var += $test['somekey'];
}
print_r($var);
You could also use any of the Assignment Operators instead of the += to do whatever you wanted!
You can try :
$var = array_map(function ($v) {
return $v['somekey'];
}, $tests);
echo implode(PHP_EOL, $var);
it seems to be picking up the last variable only
That's because $var is a variable, not an array. You're just overriding the same variable multiple times: the only value which will remain is the last one.
Convert $var to an array in your code.
$var = new array();
then use something like array_push to add the value in the array
foreach ($tests as $test) {
array_push($var, $test['somekey']);
}
finally, you may want to print out the value. echo is not the ideal way to print out an array. I'd recommend using print_r or var_dump enclosed in <pre> tags.
echo ("<pre>");
var_dump($var);
echo ("</pre>");

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

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

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