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.
Related
Example is a variable declaration within a function:
global $$link;
What does $$ mean?
A syntax such as $$variable is called Variable Variable.
For example, if you consider this portion of code:
$real_variable = 'test';
$name = 'real_variable';
echo $$name;
You will get the following output:
test
Here:
$real_variable contains 'test'
$name contains the name of your variable: 'real_variable'
$$name mean "the variable thas has its name contained in $name"
Which is $real_variable
And has the value 'test'
EDIT after #Jhonny's comment:
Doing a $$$?
Well, the best way to know is to try ;-)
So, let's try this portion of code:
$real_variable = 'test';
$name = 'real_variable';
$name_of_name = 'name';
echo $name_of_name . '<br />';
echo $$name_of_name . '<br />';
echo $$$name_of_name . '<br />';
And here's the output I get:
name
real_variable
test
So, I would say that, yes, you can do $$$ ;-)
The inner $ resolves the a variable to a string, and the outer one resolves a variable by that string.
So, consider this example
$inner = "foo";
$outer = "inner";
The variable:
$$outer
would equal the string "foo"
It's a variable's variable.
<?php
$a = 'hello';
$$a = 'world'; // now makes $hello a variable that holds 'world'
echo "$a ${$a}"; // "hello world"
echo "$a $hello"; // "hello world"
?>
It creates a dynamic variable name. E.g.
$link = 'foo';
$$link = 'bar'; // -> $foo = 'bar'
echo $foo;
// prints 'bar'
(also known as variable variable)
I do not want to repeat after others but there is a risk using $$ :)
$a = '1';
$$a = 2; // $1 = 2 :)
So use it with head. :)
It evaluates the contents of one variable as the name of another. Basically it gives you the variable whose name is stored in $link.
this worked for me (enclose in square brackets):
$aInputsAlias = [
'convocatoria' => 'even_id',
'plan' => 'acev_id',
'gasto_elegible' => 'nivel1',
'rubro' => 'nivel2',
'grupo' => 'nivel3',
];
/* Manejo de los filtros */
foreach(array_keys($aInputsAlias) as $field)
{
$key = $aInputsAlias[$field];
${$aInputsAlias[$field]} = $this->request->query($field) ? $this->request->query($field) : NULL;
}
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.
I'm curious, how does the PHP's function extract do it's work? I would like to make a slightly modified version. I want my function to make the variable names when extracting from the keys of the array from snake notation to camelCase e.g:
Now extract does this:
$array = ['foo_bar' => 'baz'];
extract($array);
// $foo_bar = 'baz';
What I would like is:
camelExtract($array);
// $fooBar = 'baz';
Now I could of course camelCase the array first, but it would be nice if this could be done in a single function.
edit:
It seems some people misread my question. Yes I could do this:
function camelExtract($array)
{
$array = ['foo_bar' => 'baz'];
$camelCased = [];
foreach($array as $key => $val)
{
$camelCased[camelcase($key)] = $val;
}
extract($camelCased);
// $fooBar = 'baz';
// I can't "return" the extracted variables here
// .. now $fooBar is only available in this scope
}
camelExtract($array);
// Not here
But as I've stated, then the $fooBar is only visible within that scope.
I guess I could do something as extract(camelCaseArray($array)); and that would work.
This should work:-
function camel(array $arr)
{
foreach($arr as $a => $b)
{
$a = lcfirst(str_replace(" ", "", ucwords(str_replace("_", " ", $a))));
$GLOBALS[$a] = $b;
}
}
You can (cautiously) use variable variables:
function camelExtract($vals = array()) {
foreach ($vals as $key => $v) {
$splitVar = explode('_', $key);
$first = true;
foreach ($splitVar as &$word) {
if (!$first) {
$word = ucfirst($word);
}
$first = false;
}
$key = implode('', $splitVar);
global ${$key};
${$key} = $v;
}
}
This has now been tested and functions as expected. This condensed answer (after it addressed the lowercase first word) also works great and is much more condensed - mine is just a little more of a "step by step" to work through how the camel is done.
extract, and modification to the callees local symbol table from within a called function is magic. There is no way to perform the equivalent in plain-PHP without using it.
The final task can be solved using John Conde's suggesting of using extra after performing a transformation to the supplied array keys; although my recommendation is to avoid extract-like behavior entirely. The approach would then look similar to
extract(camelcase_keys($arr));
where such code is not wrapped in a function so that extract is executed from the scope of the symbol table in which to import the variables.
This extract behavior is is unlike variable-variables (in a called function) and is unlike using $GLOBALS as it mutates the callees (and only the callees) symbol table as see seen in this demo:
function extract_container () {
extract(array("foo" => "bar"));
return $foo;
}
echo "Extract: " . extract_container() . "\n"; // "bar" =>
echo "Current: " . $foo . "\n"; // => {no $foo in scope}
echo "Global: " . $GLOBALS['foo'] . "\n"; // => {no 'foo' in GLOBALS}
The C implementation for extract can be found in ext/standard/array.c. This behavior is allowed because the native function does not create a new/local PHP symbol table for itself; as such it is allowed to (trivially) modify the symbol table of the calling PHP context.
<?php
$arr = array('foo_bar'=>'smth');
function camelExtract($arr) {
foreach($arr as $k=>$v) {
$newName = lcfirst(str_replace(" ","",ucwords(str_replace("_"," ",$k))));
global $$newName;
$$newName = $v;
//var_dump($newName,$$newName);
}
}
camelExtract($arr);
?>
or just like (t's what you suggest, and better to mimic the original extract)
$camelArray[lcfirst(str_replace(" ","",ucwords(str_replace("_"," ",$k))))] = $v;
and extract on the resulting camelArray
<?php
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i<=$c;$i++){
$v = '$var'.$i;
$splited = list($v) = $my_array;
}
?>
input:
$my_array
But expected output:
if I echo $var0, $var1, $var2;
hello, world, howareu
How to create dynamic PHP variables based upon the array count and then convert them into a list as a string?
You do not need list for that. $$ will suit you perfectly.
$my_array = array("hello", "world", "howareu");
foreach ($my_array as $key => $val)
{
$a = 'var'.$key;
$$a = $val;
}
echo $var0,", ", $var1,", " $var2;
Take a look here - Variable variables
Added:
or if you need count and for
for ($i = 0; $i < count($my_array); $i++)
{
$a = 'var'.$i;
$$a = $my_array[$i];
}
echo $var0,", ", $var1,", " $var2;
Of course, this line echo $var0,", ", $var1,", " $var2; sucks and looks like crap :) But in order to receive EXACTLY what you want, you need to modify variables, output like I've wrote, or use some function like implode with grue ', '.
Updated:
But if you need just that output, why not to use simple implode(', ', $my_array) :)
it's a matter of the data you need to process...if it's pretty static, you don't need the second foreach() for example, since you compare the keys anyways...
foreach($datavalueas $resultdatakey=>$resultdatavalue){
if($resultdatakey== 'A'){
//stuff for a
}
if($resultdatakey== 'B'){
//stuff for b
}
}
would become
if(isset($datavalueas['A'])){
//stuff for a
}
if(isset($datavalueas['B'])){
//stuff for b
}
since the foreach uses copies of the array, which are pretty bad for the performance...
Assuming i got your question right, you could use something like:
$array = array( 'x', 'y', 'z' );
foreach ($array as $name )
$$name = rand(1,100);
var_dump($x);
the $$ is key here, the first $ implies the variable as the second $ is used as the identifier for the variable. In this case the value being iterated over in the array. Giving us 3 variables: $x, $y, $z.
-- edit:
the correct code, besides using extract():
<?php
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i < $c;$i++){
$v = 'var'.$i;
$$v = $my_array[$i];
}
echo "$var0, $var1, $var2";
?>
You can create dynamic variables via variables variable as Mr.kovpack have stated here. In below code you can access the variables from 0 to $c-1(count of array) as per your comment to Mr.kovpack.
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i<=$c-1;$i++){
${'var'.$i} = $my_array[$i]; //Dynamic variable creation
// $splited = list($v) = $my_array;
}
echo $var0.$var1.$var2;
or you could use like below:
$my_array = array("hello","world","howareu");
$c = count($my_array);
for($i=0;$i<=$c-1;$i++){
$a='var'.$i;
$$a = $my_array[$i];
}
echo $var0."-".$var1."-".$var2;
You can read more on it here
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