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
Related
I had this question in my mind for some time. Say we have a variable:
$foo = $_GET['value']; (this is a generical example)
I wanted to know if PHP has something similar to Lua where you can have something like:
local randomvar = "string";
local foo = randomvar or 0;
This way, foo would be considered integer and if randomvar is not an integer, the value 0 will be assigned to it.
Yes, there is method is_numeric
<?
$foo = "S";
$bar = (is_numeric($foo)) ? $foo:0;
echo $bar;
?>
Please consider going through docs for your purpose http://php.net/manual/en/function.is-numeric.php
You can cast it's type:
$foo = (int) $_GET['value'];
That wouldn't set it to 0. but it would definitely remove non-numeric characters.
Or you can use is_int():
function stringToZero($var) {
return (is_int($_GET['value'])) ? $var : 0;
}
$temp = $_GET['value']; // because I'm not sure it's correct to send a $_GET to a function. might not be necessary.
$randomvar = stringToZero($temp);
unset($temp);
Don't think this exists but just want to make sure.
Is there a reverse for the .= operator in php.
example:
[$x .= $y] === [$x = $x.$y]
looking for:
[$x ? $y] === [$x = $y.$x]
No, there isn't.
The PHP manual documentation only lists two operators:
There are two string operators. The first is the concatenation operator ('.'), which returns the concatenation of its right and left arguments. The second is the concatenating assignment operator ('.='), which appends the argument on the right side to the argument on the left side.
When you want to prepend to a string, just do $str = $add . $str. There is no need for a "special operator" here. If you use it frequently and don't want to retype it every time, you can create a function like this:
function prepend($text, $add) {
return $add . $text;
}
But, as you can probably guess, it's pointess.
Amal Murali's answer gave me an idea.
function p(&$x,$y){
$x = $y.$x;
return $x;
}
Now instead of having to type out;
$var1 = $var2 . $var1;
You can just do:
p($var1, $var2);
If you send the first variable as reference it does clean the code a bit.
Variables:
$var = ' world';
$var2 = 'Hello';
Usage
echo p($var, $var2);
or
p($var, $var2);
echo $var;
is now equal to:
$var = $var2 . $var1;
echo $var;
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.
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]
Are both these PHP statements doing the same thing?:
$o =& $thing;
$o = &$thing;
Yes, they are both the exact same thing. They just take the reference of the object and reference it within the variable $o. Please note, thing should be variables.
They're not the same thing, syntactically speaking. The operator is the atomic =& and this actually matters. For instance you can't use the =& operator in a ternary expression. Neither of the following are valid syntax:
$f = isset($field[0]) ? &$field[0] : &$field;
$f =& isset($field[0]) ? $field[0] : $field;
So instead you would use this:
isset($field[0]) ? $f =& $field[0] : $f =& $field;
They both give an expected T_PAAMAYIM_NEKUDOTAYIM error.
If you meant $o = &$thing; then that assigns the reference of thing to o. Here's an example:
$thing = "foo";
$o = &$thing;
echo $o; // echos foo
$thing = "bar";
echo $o; // echos bar
The difference is very important:
<?php
$a = "exists";
$b = $a;
$c =& $a;
echo "a=".$a.", b=".$b.", c=".$c."<br/>"; //a=exists b=exists c=exists
$a = null;
echo "a=".$a.", b=".$b.", c=".$c; //a= b=exists c=
?>
Variable $c dies as $a becomes NULL, but variable $b keeps its value.
If you meant thing with a $ before them, then yes, both are assigning by reference. You can learn more about references in PHP here: http://www.php.net/manual/en/language.references.whatdo.php
Yes, they do. $o will become a reference to thing in both cases (I assume that thing is not a constant, but actually something meaningful as a variable).