How to combine two PHP variable names to call one? - php

I have multiple variables:
$Variable1 = '5/5/15';
$Variable2 = '6/13/76';
$Variable3 = '5/8/15';
...
I have an iteration variable:
$Iteration1 = 1;
while($Iteration1<=3){
echo "$Variable" . $Iteration1;
$Iteration1++;
}
desired result:
5/5/15
6/13/76
5/8/15

The Problem
Your current code echo "$Variable" . $Iteration1; tries to echo the value of the variable $Variable, which doesn't exist, and concatenate $Iteration1.
The Solution
What you want to do is build a string, "Variable" . $Iteration1 (e.g., $Variable2), then get the value of the variable with that name. This is called a "variable variable." You do this by writing ${string_you_want_to_create}, as in ${"Variable" . $Iteration1}.
Example Code For your Problem:
$Variable1 = '5/5/15';
$Variable2 = '6/13/76';
$Variable3 = '5/8/15';
$Iteration1 = 1;
while ($Iteration1 <= 3) {
echo ${"Variable" . $Iteration1} . "\n";
$Iteration1++;
}
Output:
5/5/15
6/13/76
5/8/15
Note: You could also do this in two steps, like this:
$variableName = "Variable" . $Iteration1;
echo $$variableName; // note the double $$

Try like this
echo ${"Variable" . $Iteration1};

Try this in loop
$var = 'Variable'.$Iteration1;
echo $$var.'<br>';

Related

Store the return value from an anonymous function into a variable outside its scope

$count = 2;
$amt = 4;
$str = function($count, $amt) {
return "There is ". $count . " and " . $amt;
};
echo $str . "!";
How do I store the return value from the anonymous function into a variable? I know that the entire function itself is being stored into $str which is why this doesn't work, but is there a way to?
You should simply call $str as a function:
echo $str() . "!"
Documentation for anonymous functions as php.net: http://www.php.net/manual/en/functions.anonymous.php

PHP dynamic string update with reference

Is there any way to do this:
$myVar = 2;
$str = "I'm number:".$myVar;
$myVar = 3;
echo $str;
output would be: "I'm number: 3";
I'd like to have a string where part of it would be like a pointer and its value would be set by the last modification to the referenced variable.
For instance even if I do this:
$myStr = "hi";
$myStrReference = &$myStr;
$dynamicStr = "bye ".$myStrReference;
$myStr = "bye";
echo $dynamicStr;
This will output "bye hi" but I'd like it to be "bye bye" due to the last change. I think the issue is when concatenating a pointer to a string the the pointer's value is the one used. As such, It's not possible to output the string using the value set after the concatenation.
Any ideas?
Update: the $dynamicStr will be appended to a $biggerString and at the end the $finalResult ($biggerString+$dynamicStr) will be echo to the user. Thus, my only option would be doing some kind of echo eval($finalResult) where $finalResult would have an echo($dynamicStr) inside and $dynamicStr='$myStr' (as suggested by Lawson), right?
Update:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
$finalStr = "hi ".$str();
$myVar = 3;
echo $finalStr;
I'd like for this to ouput: "hi I'm number 3" instead of "hi I'm number 2"...but it doesn't.
The problem here is that once a variable gets assigned a value (a string in your case), its value doesn't change until it's modified again.
You could use an anonymous function to accomplish something similar:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
echo $str(); // I'm number 2
$myVar = 3;
echo $str(); // I'm number 3
When the function gets assigned to $str it keeps the variable $myVar accessible from within. Calling it at any point in time will use the most recent value of $myVar.
Update
Regarding your last question, if you want to expand the string even more, you can create yet another wrapper:
$myVar = 2;
$str = function() use (&$myVar) {
return "I'm number $myVar";
};
$finalStr = function($str) {
return "hi " . $str();
}
$myVar = 3;
echo $finalStr($str);
This is a little simpler than I had before. The single quotes tell PHP not to convert the $myVar into a value yet.
<?php
$myVar = 2;
$str = 'I\'m number: $myVar';
$myVar = 3;
echo eval("echo(\"$str\");");
?>

Outputting a variable name with its value (in a function)

I would like to be able to output the name of a variable, along with that variable's value. My use case is something close to a debug situation, but I'm actually building a proof of concept for other developers and managers so we can talk about things like input filtering. Anyway...
The output HTML is currently a table, but that shouldn't matter. I can of course, just print out the name and then the contents in the HTML, but that gets tedious and is prone to typing errors. I'd like a function that I could call with the variable name, or a string with the variable name as the argument, and have that function generate the appropriate HTML for display. This doesn't appear to work.
This works:
<tr><td>$variable</td><td><?php print $variable?></td></tr>
This doesn't:
function rowFromVar($varname) {
$result = "<tr>";
$result .= "<td>\$$varname</td>";
$result .= "<td>" . $$varname . "</td>";
$result .= "</tr>";
return $result;
}
// now in the HTML...
<table><?php print rowFromVar("variable");?></table>
The variable variable $$varname is always empty. Notice that I'm passing in the name of the variable as a string, rather than trying to pass in the variable itself and work with it. I know that there be dragons that way. Instead, I'm trying to pass in the name of the variable as a string, and then use a variable variable (yeah, I know) to return the value of the original variable. That appears not to work either, and I'm betting it's a scope issue.
Is there any good way to accomplish what I'm looking for?
The variable variable $$varname is always empty. Notice that I'm
passing in the name of the variable as a string, rather than trying to
pass in the variable itself and work with it
It should be empty
Since you are passing variable as value, so:
$$varname
becomes:
$variable
and there is no value set for it.
In other words, you are just creating a variable with the name you pass as argument to function but you are not creating a value for it.
Solution:
This would work fine though if that's what you are looking to do:
function rowFromVar($varname) {
$result = "<tr>";
$result .= "<td>\$$varname</td>";
$result .= "<td>" . $varname . "</td>";
$result .= "</tr>";
return $result;
}
// now in the HTML...
<table><?php print rowFromVar("variable");?></table>
Simply remove $ from the variable on this line as done above:
$result .= "<td>" . $$varname . "</td>";
--------------------^
Did you try using $GLOBALS[$varname] instead of $$varname? Your variable in this example is at global scope, and you cannot directly access globals within a function.
You need declare your variable global within the function so that it references the global version. Adding this line at the start of your function should fix the problem:
function rowFromVar($varname) {
global $$varname;
$result = "<tr>";
$result .= "<td>\$$varname</td>";
$result .= "<td>" . $$varname . "</td>";
$result .= "</tr>";
return $result;
}
The following code should work, as you suspected scope is the main problem here.
function rowFromVar($varname, $contents) {
$result = "<tr>";
$result .= "<td>\$$varname</td>";
$result .= "<td>" . $contents . "</td>";
$result .= "</tr>";
return $result;
}
// now in the HTML...
<table><?php print rowFromVar("variable", $variable);?></table>
Please try this code:
function rowFromVar($varname) {
$result = "<tr>";
$result .= "<td>{$varname}</td>";
$result .= "<td>".$varname."</td>";
$result .= "</tr>";
return $result;
}
<table><?php echo rowFromVar("variable");?></table>
I had a similar problem, which I solved as follows.
function contents_of($string)
{
eval("global $string; \$value = $string;");
return "Variable $string has value $value";
}
$testing = 123;
echo contents_of('$testing');
// produces...
// Variable $testing has value 123

Expand PHP functions in strings just like variables

In PHP I can say
$noun = "bird";
$adjective = "warm;
echo <<<EOT
The $noun is very $adjective
EOT;
and it will output
The bird is very warm
Is there a way to do this with functions?
function getNoun() { return "bird"; }
function getAdjective() { return "warm"; }
echo <<<EOT
The getNoun() is very getAdjective()
EOT;
and output
The bird is very warm
You can use variable functions, though they're rather frowned on upon as they're not far different from variable variables...
$a = 'getNoun';
$b = 'getAdjective';
echo <<<EOT
The {$a()} is very {$b()}
EOT;
You could store it in a variable before using it:
$noun = getNoun( );
$adj = getAdjective( );
echo <<<EOT
The {$noun} is very {$adj}
EOT;
echo "The ";
echo getNoun();
echo " is very ";
echo getVerb();
Or maybe even (not 100% sure):
echo "The " . getNoun() . " is very " . getVerb();
Here is a solution using variable functions, although not exactly:
$noun=function($type){
return $type;
};
$adjective=function($adj){
return $adj;
};
echo "{$noun("Robin")} was very {$adjective("Warm")}";

Problems with strings in PHP (not adding two strings together properly)

if we say:
$termstringDomain1 = "something";
$url = "somethingelse";
$url = 'http://' . $termstringDomain1 . '/' . $url;
the result if gives me is: http:///somethingelse instead of http://something/somethingelse
so basically it is ignoring $termstringDomain1
Any idea why?
I am unable to reproduce this issue:
$foo = "foo";
$bar = "bar";
$bar = "sayFoo: " . $foo . ", sayBar: " . $bar;
print $bar; // 'sayFoo: foo, sayBar: bar'
Your problem is likely elsewhere. If I copy/paste what you provided, I get the following:
http://something/somethingelse
Check your variable casing. $domain1 is not the same as $Domain1.
Can you try putting echo infront of all the declarations, to try to track the problem down?
echo $termstringDomain1 = "something";
echo $url = "somethingelse";
echo $url = 'http://' . $termstringDomain1 . '/' . $url;

Categories