I have an array which I can only access correctly via variable variables, like so:
$foo['bar'] = "pie";
$fixed_name_variable = "foo['bar']";
echo $$fixed_name_variable;
Which in theroy echo's pie. Except it's just not returning anything. So I need to know if this approach is actually workable or if I need a rethink on it.
Just noticed. On the second line, should the bar be in quotes?
Although I hate to encourage this behaviour, you can use eval to achieve what you to a limited extent.
$foo['bar'] = "pie";
$fixed_name_variable = "foo['bar']";
$a = eval("return $$fixed_name_variable;");
echo $a; //outputs "pie"
$foo[$key_var] should work, unless I misunderstood your question?
No, I don't think this is possible. The only thing (obviously) possible is to use a variable index, and access $foo[$bar].
However, using variable variables is usually very bad practice anyway - especially because they make debugging and automatic documentation / variable lookup so terribly difficult. It's usually best not to use them, but to use an array instead.
Related
I'm fairly new to PHP and still don't know some of the most basic basics of PHP so bear with me.
When writing a script; IE: (Plz ignore syntax errors)
if isset($_POST['name']) {$Name = $_POST['nsme'];}
When using this name in the page, which way is better and loads faster??
A:) echo $Name. ' went to the river';
B:) echo $_POST['name']. 'went to the river';
Obviously this is a fictional example, I'm just wondering which way is better whether it be an echo or any other function and if anyone wouldn't mind chiming in on this, I'd be most appreciative and I thank you all once again.
Obviously
echo $_POST['name'].' went to the river';
would be faster, as you are skipping one step of assigning the post variable to a php variable.
echo $_POST['name'].' went to the river';
Will be faster as you are skipping one step.
However if you need to use $_POST['name'] multiple times, second approach will be better.
If you care about speed don't worry you can use any of them ,deference significantly low but creating variable which is used only once is not a good idea
However if you are doing
$Name = $_POST['nsme'];
and using $name variable i am sure you want to read about Singleton variable
and if you are using $name at other place too its perfectly
A direct variable access is always faster. At least the zend lexer has not recognize for dimensions...
At least for multiple uses...
(use always an isset()-check at least else you'll have notices.)
If you have var $foo and make:
$bar = $foo;
It doesn't create another copy of $foo in memory until you change $foo or $bar so you will have almost same var for both.
You will have same speed, but $bar will look better than $_POST['bar'] and with it easier to work.
Netbeans seems to suggest too many assignments is quite bad and should be changed.
i.e.
$foo = ' bar ';
$foo = trim($foo);
Should better coded as
$foo = ' bar ';
$trimmed_foo = trim($foo);
Is this acceptable? If so why? I know I can switch this particular hint type off in setting, but just checking if someone spotted anything for this.
Ths is a new warning, circa mid 2012.
Since you used the trim example I'm guessing that you have read this https://blogs.oracle.com/netbeansphp/entry/several_new_hints, which tries to explain the warning. My take on this warning is that it's trying to warn you about accidental reuse of a variable. As such it is very handy. In the trim case you give it seems a bit heavy handed. If the reassignment is on he following line, it's probably not accidental.
Ideally the variable name should describe the contents. If you are repeatedly assigning to the same variable, it suggests that the variables contents are not well defined.
Additionally, if your code has something like this:
$foo = ' bar ';
// some code, mybe 100 lines of it
// now do something with $foo
What happens if you update the code to add $foo = trim($foo); up above? You break the code below.
Those variants make no difference. If anything the first is better because it avoids cluttering the scope with variables.
I think what the warning really means is that you should try to do
$foo = trim(' bar ');
directly (or whatever $foo is really being set to in the first place), instead of storing it in a temporary. Of course, this isn't always possible.
If you don't like this hint, you can simply deactivate it in Tools -> Options -> Editor -> Hints -> PHP -> Immutable Variables
IMHO, first way is ok for more performance comparing second.
On the other hand, second approach can be more helpful if you need more descriptive variables. Also this may help more if multiple persons are working on same project.
In PHP, I get a dump of all variables like so:
var_dump(get_defined_vars());
However, in one particular application one of the variables is huge and I would really like to avoid printing it out. I could foreach over the get_defined_vars() array to create a new array and blacklist the problematic variable, but if there is a better way then I would love to know about it.
Thanks.
var_dump(array_diff_key(get_defined_vars(), array_flip(array('unwantedVar'))));
Hmm, could you just unset the var and var_dump() ?
unset($bigChuckNorrisVar);
var_dump(get_defined_vars());
Granted you might need to use that variable down your program after that, but that's a quick way to debug.
From my C++ knowledge base, I tend to initialize arrays in PHP by typing:
$foo = array()
Or I may bring this custom from Javascript, anyway, is this of any use?
As there's no problem in doing this:
$foo[45] = 'bar' without initializing it as an array, I guess not.
PS: the tags improvement is really good
Yes it is. At the very least in improves readability of code (so that you don't need to wonder 'where does $foo come from? Is it empty, or is there anything in it?`.
Also it will prevent 'Variable '$a' is not set notices, or Invalid argument passed to foreach in case you don't actually assign any values to array elements.
Either method is perfectly acceptable. As mentioned, this practice of using the array() construct is typically carried over from another language where you initialize before populating. With PHP, you can initialize an empty array and then populate later, or you can simply establish an array by assignments, such as $variableName[0] = "x";.
#petruz, that's the best way to do this, no only it will save you from nasty PHP error messages saying that function expects the parameter to be an array but, IMHO, this is the best way to write code. I initialise a variable before using it
Initializing variables before use is good practice. Even if it is not required.
I've had problems (in older versions of PHP, haven't tried recently) where I was acting on array with array_push or something and PHP barked at me. As a general rule it's not necessary, but it can be safer, especially if you're dealing with legacy code; perhaps you're expecting $foo to be an array, but it's actually a boolean? Bad things ensue.
It's good practice. Sooner or later you'll encounter a situation where you might want to do something like this:
array_push($foo, '45');
Which will throw a notice, whereas:
$foo = array();
array_push($foo, '45');
won't.
With initialization:
$myArray = array();
if ($myBoolean) {
$myArray['foo'] = 'bar';
}
return $myArray;
Without initialization:
if ($myBoolean) {
$myArray['foo'] = 'bar';
}
return $myArray;
In the first case it's clear what you want to happen if $myBoolean is false. In the second case it is not and php may throw a warning when you try and use $myArray later. Obviously this is a simplified case, but in a complex case the "if" may be a few lines down and/or not even exist until someone comes along and adds it later without realizing the array wasn't initialized.
While not necessary, I have seen lack of initialization cause non-obvious logic problems like this in complex functions that have been modified a lot over time.
Solution?
Apparently there isn't a faster way, I'm okay with that.
I am just learning php and I am trying to figure out some good tips and tricks so I don't get into a bad habit and waste time.
I am passing in values into a php script. I am using $_GET so the URL looks like this:
/poll_results.php?Sports=tennis&cat=Sports&question=Pick+your+favorite+sports
Now I know how to accept those values and place them into variables like so:
$sports = $_GET['Sports'];
$cat = $_GET['cat'];
$question = $_GET['question'];
Super simple yet if I am passing 5 - 6 things it can get bothersome and I don't like typing things out for every single variable, that's the only reason. I know there is a better way of doing this. I have tried list($var, $var, $var) = $_GET but that doesn't work with an associative array just indexed ones (i think).
I also tried variable variables like so:
foreach($_GET as $value) {
$$values = $value;
echo $$values;
}
But that gave me a Notice: Undefined variable: values in poll_results.php on line 14. Line 14 is the $$values = $value. I don't know if that's a big deal or not... but I'm not turning off error reporting as I am still in the process of building the script. It does do what I want it to do though...
Any answers will be copied and pasted into my question so the next person knows :D
Thanks guys!
Your second bit of code is wrong. It ought to be like
foreach ($_GET as $key => $value) {
$$key = $value;
}
if i understand your intent. However, you're basically reinventing register_globals, which....eh. That'll get ya hacked.
If you have certain variables you want to get, you could do like
foreach (array('Sports', 'cat', 'question') as $key)
{
$$key = $_GET[$key];
}
which is less likely to overwrite some important variable (whether by accident or because someone was messing around with URLs).
Use parse_url() to extract the query string from a URL you've got in a string, then parse_str() to extract the individual arguments of the query string.
If you want to pollute your script with the contents of the superglobals, then you can use extract(). however, be aware that this is basically replicating the hideous monstrosity known as "register_globals", and opens all kinds of security vulnerabilities.
For instant, what if one of the original query arguments was _GET=haha. You've now trashed the $_GET superglobal by overwriting it via extract().
I am just learning php and I am trying to figure out some good tips and tricks so I don't get into a bad habit and waste time.
If I am passing 5 - 6 things it can get bothersome and I don't like typing things out for every single variable, that's the only reason.
What you are trying to do will, unless curbed, become a bad habit and even before then is a waste of time.
Type out the variables: your digits like exercise and your brain can take it easy when it doesn't have to figure out which variables are available (or not, or maybe; which would be the case when you use variable variables).
You can use
foreach($_GET as $key => $value)
To preserve the key and value associativity.
Variable variables (the $$value) are a bad idea. With your loop above say you had a variable named $password that is already defined from some other source. Now I can send $_GET['password'] and overwrite your variable! All sorts of nastiness can result from this. It's the same reason why PHP abandoned register_globals which essentially does the same thing.
My advice: use $_POST when possible. It keeps your URLs much cleaner for one thing. Secondly there's no real reason to assign the array to variables anyway, just use them where you need them in the program.
One good reason for this, especially in a large program, is that you'll instantly know where they came from, and that their data should not be trusted.