Merge two variable values to get a new variable name (not value) - php

is possible in php to merge the first variable value with the second variable value to get a new variable name (not value).
$1 = test
$2 = 5
//do magic results in new variable name eg. $($1+$2)
$test5 = true
So if $2 is dynamic we get a dynamic variable name, not a dynamic value. The value "true" is just an example value. I don't know If it is possible, because I'm completely new to PHP and found nothing by searching.

Yes. Use {} after the $ sign to interpret the inner content as the variable name.
$a = "test";
$b = 5;
${$a . $b} = "new value";
echo "test5 = " . $test5; // prints test5 = new value
See manual page for more details.

Related

Variable without name: ${''}

So variable variables are existing. Meaning that this is working
$a = 'test';
$$a = 'Hello';
echo ${'test'}; //outputs 'Hello'
But now I've come across some rather strange code using a variable without a name:
function test(&$numRows) {
$numRows = 5;
echo ' -- done test';
}
$value = 0;
test($value);
echo ' -- result is '.$value;
test(${''}); //variable without name
http://ideone.com/gTvayV Code fiddle
Output of this is:
-- done test -- result is 5 -- done test
That means, the code is not crashing.
Now my question is: what exactly happens if $numRows value is changed when the parameter is a variable without name? Will the value be written into nirvana? Is that the PHP variable equivalent to /dev/null?
I wasn't able to find anything specific about this.
Thanks in advance
${''} is a valid variable which name happens to be an empty string. If you have never set it before, it is undefined.
var_dump(isset(${''})); // if you have never set it before, it is undefined.
You don't see any error because you disabled the NOTICE error message.
error_reporting(E_ALL);
ini_set('display_errors', 1);
echo ${''}; // Notice: Undefined variable:
You can set it like this:
${''} = 10;
echo ${''}; // shows 10
Now my question is: what exactly happens if $numRows value is changed
when the parameter is a variable without name?
There's no such thing as a variable without name, an empty string in PHP is a totally valid name.
Maybe I'm wrong, but in PHP, all varibles can be accessed by their names (or more precisely, the string representation of their name), and since an empty string is still a string, it counts as a valid name.
Think about variables like an array key-value pair. You can create an array key with an empty string:
$arr = [];
$arr[''] = 'appul';
var_dump($arr['']); // prints: string(5) "appul"
$arr[''] = 'ponka';
var_dump($arr['']); // prints: string(5) "ponka"
Whenever you access $arr[''], you address the same value.
You can access all variables as a string using the $GLOBAL variable too, so you can examine what happens to your "nameless" variable:
${''} = 'ponka';
var_dump($GLOBALS['']); // prints: string(5) "ponka"
${''} = 'appul';
var_dump($GLOBALS['']); // prints: string(5) "appul"
Will the value be written into nirvana? Is that the PHP variable equivalent to /dev/null? I wasn't able to find anything specific about this.
No, it doesn't go to nirvana, it sits quietly in the global space, and it's a little bit trickier to access it, but otherways, it's a normal variable like any others.

Get a variable name from database

I'm a little confused - how do I get a variable name stored to a database?!
Record in the database is a string: "$test"
The variable $user is set before the records a fetched from database. So I want to "convert" this string to a real variable to get the value of it.
The following didn't work:
// $test is set to 'bla'
$test = 'bla';
// $var is the value from the database
$var = '$test';
// print $test
echo ${$var};
I know that it would work if I remove the '$' from the database record
$var = 'test';
echo $$var;
But how to handle this without?
String replace in better option, if you don't want to replace $ you can use eval function:
$test = 'bla';
$var = '$test';
eval("\$var = \"$var\";");
echo $var; //output: bla
I was facing a similar problem just now.
Here is what I did:
$res[0] is obtained from mysql_fetch_array() and it contains another query which has $variable embedded.
$qry="select query from sql_list where id=".$sql_id;
$result=mysql_query($qry);
$res=mysql_fetch_array($result);
eval("\$qry_2 = \"$res[0]\";");
mysql_query($qry_2)
It works! Maybe someone can suggest a better way.
This is 3 years later but since no one give you your answer, maybe this will help you or the next person searching for this.
From what I understand, you already declared a variable and stored the name of that var in the db.
$var = '$test'; // from db
$var[0] = ''; // remove first letter, simple & much faster than ( trim or substr )
//content of var
$var_content = ${$var};

Add two $row together in one php echo

I'm not even sure if what I am trying to do is possible, I have a simple php echo line as below..
<?php echo $T1R[0]['Site']; ?>
This works well but I want to make the "1" in the $T1R to be fluid, is it possible to do something like ..
<?php echo $T + '$row_ColNumC['ColNaumNo']' + R[0]['Site']; ?>
Where the 1 is replaced with the content of ColNaumNo i.e. the returned result might be..
<?php echo $T32R[0]['Site']; ?>
It is possible in PHP. The concept is called "variable variables".
The idea is simple: you generate the variable name you want to use and store it in another variable:
$name = 'T'.$row_ColNumC['ColNaumNo'].'R';
Pay attention to the string concatenation operator. PHP uses a dot (.) for this, not the plus sign (+).
If the value of $row_ColNumc['ColNaumNo'] is 32 then the value stored in variable $name is 'T32R';
You can then prepend the variable $name with an extra $ to use it as the name of another variable (indirection). The code echo($$name); prints the content of variable $T32R (if any).
If the variable $T32R stores an array then the syntax $$name[0] is ambiguous and the parser needs a hint to interpret it. It is well explained in the documentation page (of the variable variables):
In order to use variable variables with arrays, you have to resolve an ambiguity problem. That is, if you write $$a[1] then the parser needs to know if you meant to use $a[1] as a variable, or if you wanted $$a as the variable and then the [1] index from that variable. The syntax for resolving this ambiguity is: ${$a[1]} for the first case and ${$a}[1] for the second.
You can do like this
$T1R[0]['Site'] = "test";
$c = 1;
$a = "T".$c."R";
$b = $$a;
echo "<pre>";
print_r($b[0]['Site']);
Or more simpler like this
$T1R[0]['Site'] = "test";
$c = 1;
$a = "T".$c."R";
echo "<pre>";
print_r(${$a}[0]['Site']);

Setting a value to variable

I have a problem assigning value to a variable in php.
Example what I am trying to do:
Suppose I have 3 variables and I want to assign the value of 3rd variable to 4th variable but in 3rd variable I want to use first 2 variables.
$depth = 1;
$forumcat = _cat;
$f1_cat = 'some html code';
$new = '';
Now I want to assign $f1_cat to $new variable
I know it can be done like $new = $f1_cat but I want to do it like
$new = $f$depth$forumcat;
I mean in place of using '1_cat' I want to use the variables.
I tried the following
$new = "\$f{$depth}{$forumcat}";
but this statement assigns a string $f1_cat but I want to assign $f1_cat variable value.
How to do it?
$new = ${'f'.$depth.$forumcat}; // This will contain value of $f1_cat
Also you may want to change $forumcat = _cat; to $forumcat = '_cat';. please note the single quotes added to _cat

Dynamically created Variables in PHP produce occasionally names like "_GET" or "_POST" instead of the variable names

I have a function from which I call many different variables, and produce another (dynamically created) return variable.
All good. (I explain my Problem below this PHP 5.3 example)
function showArrayIntersection($ar1, $ar2) {
$dynamicName = array_search($ar1, $GLOBALS) . '_' . array_search($ar2, $GLOBALS);
global ${$dynamicName};
${$dynamicName} = implode(array_values(array_intersect($ar1, $ar2)));
}
$Bankers = [6,7,0,6,5,6,2]; // `[]` is equivalent to `array()` introduced in PHP 5.4
$Bond = [6,7,0,5,0];
$Politicians = [4,6,1,6,4,6,3];
$James = [0,1,0,3,7];
showArrayIntersection($James, $Bond);
showArrayIntersection($Bankers, $Politicians);
echo "Moneysystem: $Bankers_Politicians\n";
echo "Moneypenny : $James_Bond\n";
Output:
Moneysystem: 666
Moneypenny : 007
This works most of the time well, but sometimes only instead of a variable name like $James_Bond I get a variable name like POST_POST or GET_GET, meaning instead of the name James or Bond PHP returns either a "_GET" or a "_POST".
Since AbraCadaver asked full of solicitousness: "What in the world are you doing?"
here my solution and explanation:
Einacio: I coudn't create the names on the fly because the already arrive from a first function dynamically, so the actual variable name is not the true name.
And AbraCadaver pointed out that array_search() does not accept an array; unfortunately for sake of brevity I omitted that I pass on as a first argument not an array but another dynamic created variable from the root - I didn't want to make it too complicated, but basically it works like this:
function processUsers ($userName , $request2send ){
global ${$user.'_'.$request2send};
$url2send = "http...?request=".$request2send ;
...
$returnedValue = receivedDataArray ();//example elvis ([0] => Presley );
${$user.'_'.$request2send} = $returnedValue;
}
--- now Now I get the value of the function in the root ---
$firstValue = processUsers ("cuteAnimal" , "getName");
// returns: $cuteAnimal_getName = "Mouse"
and
$secondValue = processUsers ("actorRourke" , "getFirstName");
// returns: $actorRourke_getFirstName = "Mickey";
And now the bummer - a second function which needs the first one to be completed:
function combineValues ($firstValue , $secondValue ){
global ${$firstValue.'AND'.$secondValue};
${$firstValue.'_'.$secondValue} = $firstValue." ".$secondValue;
}
// returnes $actorRourke_getFirstNameANDcuteAnimal_getName = "Mickey Mouse";
Of course the second function is much more complicated and requires first to be completed,
but I hope you can understand now that it is not an array directly which I passed on but dynamic variable names which I could not just use as "firstValue" but I needed the name "actorRourke_getFirstName".
So AbraCadaver's suggestion to use $GLOBALS[..] did not work for me since it requires arrays.
However: Thanks for all your help and I hope I could now explain the issue to you.
Argument 1 for array_search() does not accept an array.
print_r($GLOBALS); will show the empty $_GET and $_POST arrays.
What in the world are you doing?
To go with Einacio:
function showArrayIntersection($ar1, $ar2) {
$GLOBALS[$ar1 . '_' . $ar2] = implode(array_intersect($GLOBALS[$ar1], $GLOBALS[$ar2]));
}
showArrayIntersection('James', 'Bond');
echo "Moneypenny : $James_Bond\n";
You could check to make sure they exist of course isset().
how about just using the names of the variables? it would also avoid value conflicts
function showArrayIntersection($ar1, $ar2) {
$dynamicName = $ar1 . '_' . $ar2;
global ${$dynamicName};
${$dynamicName} = implode(array_values(array_intersect($_GLOBALS[$ar1], $_GLOBALS[$ar2])));
}
$Bankers = [6,7,0,6,5,6,2]; // `[]` is equivalent to `array()` introduced in PHP 5.4
$Bond = [6,7,0,5,0];
$Politicians = [4,6,1,6,4,6,3];
$James = [0,1,0,3,7];
showArrayIntersection('James', 'Bond');
showArrayIntersection('Bankers', 'Politicians');
echo "Moneysystem: $Bankers_Politicians\n";
echo "Moneypenny : $James_Bond\n";

Categories