PHP: New variable from string concatenated with variable (variable-variables) - php

I am having a basic php problem that I haven't been able to resolve and I would also like to understand WHY!
$upperValueCB = 10;
$passNodeMatrixSource = 'CB';
$topValue= '$upperValue'.$passNodeMatrixSource;
echo $topValue;
OUTPUT
$upperValueCB
but I want OUTPUT as the variable's value 10.
How can I make PHP read the $dollar-phrase as a variable and not a string?

$varName = 'upperValue' . $passNodeMatrixSource;
$topValue = $$varName;
http://php.net/manual/en/language.variables.variable.php

This little example might illustrate what you are about to do:
<?php
$a = 'b';
$b = 10;
echo ${$a}; // will output 10
So you will have to change your example to:
$upperValueCB = 10;
$passNodeMatrixSource = 'CB';
$topValue= 'upperValue'.$passNodeMatrixSource;
echo ${$topValue}; // will output 10

You can do it this way :
$upperValueCB = 10;
$passNodeMatrixSource = 'CB';
$topValue= ${'upperValue'.$passNodeMatrixSource};
echo $topValue;
Because upperValueCB is the var name, if you want PHP to understand which var to use, you have to give the var name.
For that, you can use static way like $upperValueCB
or using a string like this : ${'upperValueCB'}
or using a third var containing the var name $var = 'upperValueCB'; $$var;

$upperValueCB = 10;
$passNodeMatrixSource = 'CB';
$topValue= 'upperValue'.$passNodeMatrixSource;
echo ${$topValue};

Related

PHP - Stop need to create hundreds of variables

I'm writing a script and it seems like a bit of a ballache so I came on SO to ask for a little help making my script more dynamic so I create a better version of what I'm doing. I've read into variable variables but I'm still stuck on how I'd use them.
I'll obviously shorten this down but my current script is:
$a0 = $tags['items'][0]['snippet']['tags'];
$a1 = $tags['items'][1]['snippet']['tags'];
$a2 = $tags['items'][2]['snippet']['tags'];
if (!is_array($a0)) { $a0 = array(); }
if (!is_array($a1)) { $a1 = array(); }
if (!is_array($a2)) { $a2 = array(); }
$a0 = array_map('strtolower', $a0);
$a1 = array_map('strtolower', $a1);
$a2 = array_map('strtolower', $a2);
array_count_values(array_merge($a0,$a1,$a2));
I'm looking for a way to dynamically create the variables (For example using an index in a while loop rather than creating these variables uniquely. This obviously is fine on a small scale, but i've currently done 50 of these for each and it's causing serious time problems. Any help is much appreciated
Treat the whole $tags variable as an array and you can do this, similar to the strtolower array_map you have already:
$tagItems = [];
foreach($tags['items'] as $item) {
if (!$item['snippet']['tags'] || !is_array($item['snippet']['tags'])) {
continue;
}
foreach($item['snippet']['tags'] as $tag) {
$tag = strtolower($tag);
if (!isset($tagItems[$tag])) {
$tagItems[$tag] = 0;
}
$tagItems[$tag]++;
}
}
As #FranzGleichmann says, try not to use variable variables, which are a smell and potential security risk, but instead rethink how you want to approach the problem.
You should be able to produce the same output that you get from array_count_values with a nested foreach loop.
foreach ($tags['items'] as $x) { // loop over the list of items
foreach ($x['snippet']['tags'] as $tag) { // loop over the tags from each item
$tag = strtolower($tag);
if (!isset($counts[$tag])) $counts[$tag] = 0;
$counts[$tag]++; // increment the tag count
}
}
No need to create 100 variables. That would cause a headache. Instead, use a simple loop function.
$b = array();
for ($n=1; $n<=100; $n++) {
$a = $tags['items']["$n"]['snippet']['tags'];
if (!is_array($a)) { $a = array(); }
$a = array_map('strtolower', $a);
array_count_values(array_merge($b,$a));
}
I hope it works! Have a nice coding
I would write this in a comment but i will a long one,
Variable Variable, is simply the value of the original var assigned as a var name, which means:
$my_1st_var = 'im_1st';
//use $$
$$my_1st_var = 'im_2nd'; //that is the same of $im_1st='im_2nd';
//results
echo $my_1st_var; // >>> im_1st
echo $im_1st; // >>> im_2nd
that means i created a new var and called it the value of the 1st var which is im_1st and that makes the variable name is $im_1st
also you can set multiple values as a var name:
$var0 = 'a';
$var1 = 'b';
$var2 = 'c';
$var3 = '3';
//we can do this
${$var0.$var1} = 'new var 1'; //same as: $ab = 'new var 1';
${$var1.$var2.$var3} = 'im the newest'; //same as: $bc3 = 'im the newest';
//set a var value + text
${$var0.'4'.$var1} = 'new?'; //same as: $a4b = 'new?';
also $GOLBALS[]; is some kind of $$
hope it helps you understanding what is hard for you about $$ ;)
Alright so dynamically creating variables is easy is a script language like PHP.
You could make $a an array, and instead of $a0, $a1, ... use $a[$i] where $i goes from 0 to 50 or more.
Or you could use this nice funky syntax: ${'a'.$i}. For example:
$i = 0;
${'a'.$i} = 'foobar';
echo $a0; // will output foobar
However you shouldn't do any of this.
What you should do is think about what you are trying to achieve and come up with a different algorithm that doesn't require dynamically named variables.
In this case, something like this looks like it would do the job:
$result = [];
foreach ( $tags['items'] as $item ) {
if ( is_array($item['snippet']['tags']) ) {
$result = array_merge($result, array_map('strtolower',$item));
}
}
array_count_values($result);
This is obviously not tested and from the top of my head, but I hope you get the idea. (EDIT: or check the other answers with similarly rewritten algorithms)

Iterate on PHP variable (list/array) then output the index based on its value

Using the following example in PHP:
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
1) I would like to iterate on the 4 values in $priv. Would 'foreach' be the correct way to do it?
2) If the value is higher than a given number, I would like to echo the index of this value. Not sure how to do it. The comparaison must be INT (not string).
Ex. using "30" it would output:
PAGE_C
PAGE_D
Is it possible? Or maybe I am not using the correct container for what I'm trying to do ?
PS. How would you call the type of "$priv" in this example ? An array ? An indexed variable ? A dictionary ? A list ?
Thank you.
basically:
<?php
function foo($var){
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
$out='';
foreach ($priv as $k=>$v){
if ($v >$var){
$out .= $k.'<br>';
}
}
return $out;
}
echo foo('30');
demo: http://codepad.viper-7.com/GNX7Gf
Just create an array with the letters to iterate over.
$letters = array('A','B','C','D');
for($i=0;$i<count($letters);$i++) {
if($priv['PAGE_' . $letters[$i]] > /*value*/) {
echo $priv['PAGE_' . $letters[$i]];
}
}
$priv is an array.
Also, it's not too clear to me what you are exactly trying to do. Are you trying to echo the value of the array element if it's greater than a constant value?
We could do it using PHP builtin array functions. Its good to use builtin functions if possible in case of performance.
array_walk will do the trick for you. In this case $priv is an associative PHP array. Following is the one line script that will do what you want to achieve:
$input = 30;
$priv['PAGE_A'] = 11;
$priv['PAGE_B'] = 22;
$priv['PAGE_C'] = 33;
$priv['PAGE_D'] = 44;
array_walk($priv, function($value, $key, $input){ if($value > $input) echo $key . '<br>';}, $input);

Change rawtext to a variable name?

Is there a way I could possible change raw text to a variable name in a echo. For instance settings a variable $number to number1, and then when it echoes to use $number1?
To clarify, say we have a variable named $number = "number1"; in it, and when we echo $number , it echos a variable named number1, how would I change number1 to a variable? Something like "echo "$"."$number";?
You can try the following
$number = 2012 ;
$name = 'number' ;
echo $$name ; //2012
echo ${$name}; //2012
echo ${"number"} ; //2012
echo "${$name}"; //2012
Quite easily:
$number = 'number1';
$$number = '';
var_dump(get_defined_vars());
or
echo $number1;
You can do this with two dollars instead of one. Note that this is really bad practice, and there's probably a better way to achieve your goal here.
$number = 42
$usenumber = 'number'
echo $$usenumber //echos 42

Concatenate strings for variable identifier in PHP

I know this is not the proper way to do this, however I am trying to put a quick fix on a form that was done by another developer. Basically I want to add an incremental number to a variable inside a while statement:
$count = 1;
while ($r = mysql_fetch_array($query)) {
$variable . $count = $r['somefield'];
$count++
}
So that makes the variables:
$variable1
$variable2
$variable3
....etc
$varname = 'variable' . $count;
$$varname = $r['somefield'];
http://www.php.net/manual/en/language.variables.variable.php
You'd be better off with an array...
$variable[] = $r['somefield'];
You can use variable variables, however it is probably not a good idea, especially for a trivial case like this one.

PHP concatenate variable

Might be an easy question for you guys. can't find it on google.
I am trying to concatenate two variables name;
$i=0;
for ($i=0;$i<5;$i++){
if($array[$i]>0){
$test.$i=//do something
}else{
$test.$i=//do something
}
}
//echo $test0 gives me nothing.
//echo $test1 gives me nothing.
I know I can't use $test.$i but don't know how to do this.Any helps? Thanks!
try ${$test.$i} = value
EDIT: http://php.net/manual/en/language.variables.variable.php
I'm assuming that the variables are called $test0, $test1, ..., $test5. You can use the following:
${"test".$i}
Though, might I suggest that you make $test an array and use $i as the index instead? It's very odd to use $i as an index to loop through a list of variable names.
As an example, instead of:
$test0 = "hello";
$test1 = "world";
Use:
$test[0] = "hello";
$test[1] = "world";
Try this:
for ($i=0;$i<5;$i++){
$the_test = $test.$i;
if($array[$i]>0){
$$the_test=//do something
}
else{
$$the_test=//do something
}
}
This might work:
$varName = $test . $i;
$$varName = ...
Can i ask where for this is neccesary?

Categories