I have got a variable called $Title
It is possible that the variable contains a string,
example A: 'Foo'
But the variable can also contain a reference to an different variable,
example B: '$Foo'
When I use print $Title php returns 'Foo' (EX A) or '$Foo' (EX B) as an string.
When I use print $$Title php tries to return the value of a variable named $Foo (EX A) or $$Foo (EX B)
I want to accomplish the following:
When $Title contains just a string, print that string
When $Title contains the reference to a variable, look up that variable and show its content
I could just look for the first character in the string. When it is $ use echo $$Title ELSE use echo $Title, but it is possible that $Title contains something like this:
$Title = '$Foo . \'Bar\' . $Bar . \'Foo\'';
In that case $Foo and $Bar are variables and need to act as such, 'Bar' and 'Foo' are strings and need to act as such.
How can I make this able to work??
A string is always just a string. A string is never a variable.
Case 1, a plain string:
$foo = 'bar';
echo $foo; // bar
echo $$foo; // content of $bar if it exists
Case 2, a "variable in a string":
$foo = 'bar';
$bar = "$foo"; // $bar is now the string 'bar', the variable is interpolated immediately
echo $bar; // bar
echo $$bar; // bar (content of $bar)
Case 3, a string with a dollar in it:
$foo = '$bar';
echo $foo; // $bar
echo $$foo; // invalid variable name "$bar"
$$foo resolves to the variable name $$bar, which is an invalid name.
You cannot have "variables in strings". Writing "$foo" immediately interpolates the value of $foo and gives you back a new string.
Just maybe, you want this:
$foo = 'bar'; // the string "bar"
$baz = '$foo'; // the string "$foo"
// MAGIC
echo $baz; // echoes "bar"
I.e., if your string contains a dollar followed by the name of a variable, you want to substitute that value. First I'd say this is a bad idea. Then I'd say you will have to extract all those "dollar strings" out of your string, check if the variable exists, then replace the value in the string using normal string manipulation. Yes, you could do it using eval, but no, that's not a good idea. For the above code, something like this'll do:
if ($baz[0] == '$') {
$varName = substr($baz, 1);
if (isset($$varName)) {
$baz = $$varName;
}
}
The is_string PHP function is used to check if a value is a string. This could be used within an if () statement to treat strings in one way and non-strings in another. It will return true or false.
<?php
if (is_string(23))
{
echo "Yes";
} else {
echo "No";
}
?>
The code above should output "No" because 23 is not a string. Let's try this again:
<?php
if (is_string("Hello World"))
{
echo "Yes";
} else {
echo "No";
}
?>
Since "Hello World" is a string, this would echo "Yes".
Use a if statement to check if the $variable is a string..
if(is_string($var)) {
echo $var;
} else {
// What do you want to achieve here?
}
Code like this:
$Title = '$Foo . \'Bar\' . $Bar . \'Foo\'';
can't be evaluated when you try to print it, it's evaluated at the moment of assignment. The reason variable names are not being replaced by their values in your case are single quotes.
$a = 1;
$b = 2;
$var = '$a + $b'; // this is a string
echo $var; // $a + $b
$var = "$a + $b"; // this is also a string, but variables will be processed
echo $var; // 1 + 2
Note, that in second scenario it only processes the variable names, it doesn't run the code ('+' is a string, not an operation).
If you want to keep the '$a + $b' as a string within your $title and evaluate it as a PHP code at the moment, when you print it, you need to use eval function. However, I strongly suggest trying to avoid using this function as much as possible.
As I can understand, string may be just string or some sort of variable 'reference'.
Will this work for you or there is always $ if variable reference?
$var1='test';
$ref1='var1';
if(isset($$ref1)) {
// variable exists
}
else {
// no such variable
}
You can use the dangerous eval php contruct. But be warned if any of the string is coming from a user input
$string = 'cup';
$name = 'coffee';
$str = 'This is a $string with my $name in it.';
echo $str. "\n";
eval("\$str = \"$str\";");
echo $str. "\n";
This is just a copy and paste from (PHP eval documentation)[http://php.net/manual/en/function.eval.php]
Related
Say I had the variable $foo which has a value of "bar" and I wanted to make a variable variable from it, but also append the string "123" to it, so that the variable name is $bar123. How would I do this?
I already know that $$foo = "abc123" would make a variable $bar with the value of "abc123", but I don't know how to append a string to this variable name.
Using variable variables, you can do something as the following:
<?php
$a = "foo";
$number = 123;
$b = $a . "$number";
$$b = "Hello World!";
echo ${$b};
However, as #smith said, it is better to use associative arrays here.
I realised the solution was fairly simple:
$foo = "bar";
$x = $foo . "123"
$$x = "random important variable value"
I'm wondering if it is possible to update a variable which is inside another variable.
Here is an example:
$t = 15;
$dir ='foo and some more text'.$t.'and more foo';
$t = 10;
print_r($dir);
For me $dir outputs $t as 15 not as 10.
Can anyone help me with this?
You're misunderstanding what that code is actually doing. This line:
$dir ='foo and some more text'.$t.'and more foo';
doesn't store a reference to $t for future evaluation. It evaluates $t to whatever value it has at that time and uses the result to construct the value placed in $dir. Any reference to $t is lost before the engine even gets to the step of assigning it to $dir.
You can pass a variable to a function, you can encapsulate variable state in an object, but an evaluated string doesn't reference a variable.
This is not possible. But you can make something similar with preg_match and a custom print function.
This is an just example how it could be done (warning: experimental):
<?php
$blub = 15;
$test = 'foo and some more text %blub and more foo %%a';
function printv($text) {
$parsedText = preg_replace_callback('~%([%A-Za-z0-9]+)~i', function($matches) {
if ($matches[1][0] != '%') {
return $GLOBALS[$matches[1]];
}
return $matches[1];
}, $text);
echo $parsedText;
}
$blub = 17;
printv($test);
?>
What ever be the value of $t at the time of assigning $dir the value is 15. That will be stored and assigned. This is same for all the languages.
Or if you want to, its easy to do it with anonymous function.
$dir = function ($t) {return 'foo and some more text'.$t.'and more foo';}
echo $dir(10);
//foo and some more text10and more foo
echo $dir(15);
//foo and some more text15and more foo
I have encountered the need to access/change a variable as such:
$this->{$var}
The context is with CI datamapper get rules. I can't seem to find what this syntax actually does. What do the {'s do in this context?
Why can't you just use:
$this->var
This is a variable variable, such that you will end up with $this->{value-of-$val}.
See: http://php.net/manual/en/language.variables.variable.php
So for example:
$this->a = "hello";
$this->b = "hi";
$this->val = "howdy";
$val = "a";
echo $this->{$val}; // outputs "hello"
$val = "b";
echo $this->{$val}; // outputs "hi"
echo $this->val; // outputs "howdy"
echo $this->{"val"}; // also outputs "howdy"
Working example: http://3v4l.org/QNds9
This of course is working within a class context. You can use variable variables in a local context just as easily like this:
$a = "hello";
$b = "hi";
$val = "a";
echo $$val; // outputs "hello"
$val = "b";
echo $$val; // outputs "hi"
Working example: http://3v4l.org/n16sk
First of all $this->{$var} and $this->var are two very different things. The latter will request the var class variable while the other will request the name of the variable contained in the string of $var. If $var is the string 'foo' then it will request $this->foo and so on.
This is useful for dynamic programming (when you know the name of the variable only at runtime). But the classic {} notation in a string context is very powerful especially when you have weird variable names:
${'y - x'} = 'Ok';
$var = 'y - x';
echo ${$var};
will print Ok even if the variable name y - x isn't valid because of the spaces and the - character.
Hello I am new to PHP and I don't know exactaly what does this code means
$de = array('Ä'=>'ae','ä'=>'ae','Ü'=>'ue','ü'=>'ue', 'Ö'=>'oe', 'ö'=>'oe', 'ß'=>'ss');
strtr($str, ${$de});
The only thing that I need to know is what does ${$de} mean?
It's a variable variable, one of the most intriguing part of the php implementation.
Sometimes usefull, always confusing:
$Bar = "a";
$Foo = "Bar";
$World = "Foo";
$Hello = "World";
$a = "Hello";
$a; //Returns Hello
$$a; //Returns World
$$$a; //Returns Foo
$$$$a; //Returns Bar
$$$$$a; //Returns a
$$$$$$a; //Returns Hello
$$$$$$$a; //Returns World
....
That's a variable variable.
http://php.net/manual/en/language.variables.variable.php
Known as Variables Variable
http://php.net/manual/en/language.variables.variable.php
I know you can do: $hash('foo') and $$foo and also $bar[$foo], what are each of these things called?
$hash('foo') is a variable function.
$hash may contain a string with the function name, or an anonymous function.
$hash = 'md5';
// This means echo md5('foo');
// Output: acbd18db4cc2f85cedef654fccc4a4d8
echo $hash('foo');
$$foo is a variable variable.
$foo may contain a string with the variable name.
$foo = 'bar';
$bar = 'baz';
// This means echo $bar;
// Output: baz
echo $$foo;
$bar[$foo] is a variable array key.
$foo may contain anything that can be used as an array key, like a numeric index or an associative name.
$bar = array('first' => 'A', 'second' => 'B', 'third' => 'C');
$foo = 'first';
// This tells PHP to look for the value of key 'first'
// Output: A
echo $bar[$foo];
The PHP manual has an article on variable variables, and an article on anonymous functions (but I didn't show an example above for the latter).