PHP array as variable? - php

I'm new to PHP, I have this code:
if(!$form['profile_hunter']['field_profile_hunter_location']['und']['0']['value']['#default_value']){
$form['profile_hunter']['field_profile_hunter_location']['und']['0']['value']['#default_value'] = $default_city;
}
it's working but I don't like it to be that long, so I change:
$form_location = $form['profile_hunter']['field_profile_hunter_location']['und']['0']['value']['#default_value'];
if(!$form_location){
$form_location = $city;
}
Then it's not working, why?

It's because when you assign $form_location, it is making a copy of the data. In order for both variables to "point" to the same data, you would need to use the reference operator, example:
$var = &$some_var;
and in your case:
$form_location = &$form['profile_hunter']['field_profile_hunter_location']['und']['0']['value']['#default_value'];
if(!$form_location){
$form_location = $default_city;
}
http://php.net/manual/en/language.references.php

Because your code is assigning to $form_location, but not the actual value in the array.
The assignment makes $form_location refer to something different. The fact that its former value happened to be copied out of an array is irrelevant.
In C/C++, you could do something like this using pointers, but most higher level languages don't support it since it tends to be error prone.
Anyway, you could set a variable to the innermost array, since arrays are stored by reference. This would reduce the amount of code you need, while avoiding the problems introduced by taking a reference directly to an array element.

$form_location = $form['profile_hunter']['field_profile_hunter_location']['und'][0]['value']['#default_value'];
if(empty($form_location)){
$form['profile_hunter']['field_profile_hunter_location']['und'][0]['value']['#default_value'] = $city;
}
You should probably use 'empty', that is a Drupal convention. Also "0" is not a string, but a number, so you don't need quotes around it.

Got the answer! Thanks to Tony!
It should be
$form_location = &$form['profile_hunter']['field_profile_hunter_location']['und']['0']['value']['#default_value'];
The "&" means to pass by reference, without it would be to pass by value.

Related

Is it necessary or useful to initialize sub-arrays in PHP?

Let's say I have a variable which is an initialized, empty array.
$cache = [];
The data in this array can be created like this, for example (please excuse the crude code and variable/key names, they're here for the sake of this example only):
for ($row in $someOtherArray) {
$cache[$row['id']][] = $row['data'];
}
Since $cache is a PHP array, I don't really need to initialize $cache[$row['id']] to also be an array. However, I sometimes encounter code like this:
for ($row in $someOtherArray) {
if (!isset($cache[$row['id']])) {
$cache[$row['id']] = [];
}
$cache[$row['id']][] = $row['data'];
}
Above, the sub-array is explicitly initialized as an empty array. Is it useful somehow? For example - does it help the interpreter in some way? Or is it only a developer being overzealous?
It's unnecessary as far as PHP is concerned. PHP will implicitly create any number of sub-arrays for you using the $foo[$bar][] syntax. It may be required for business logic, though not in this particular arrangement; it's simply redundant here. If the value assignment is somehow separate logic, but you still want to ensure that at least an empty array exists for the key, that's the only time it makes sense.
Once you have initialised a variable as an array, you can use array specific methods on that variable. For example array_push(), array_map() etc..

php variable in an array

$q2=$_REQUEST['binge'];
'book2'=>array('callno'=>123006,'price'=>number_format(844,2),'desc'=>'Binge','auth'=>'Tyler Oakley','quant'=>$q2,'total'=>number_format(844,2)*$q2)
On this particular code, It kept displaying errors like this
Warning: A non-numeric value encountered in C:\xampp\htdocs\Webcard_3new\Webcard\wishlist.php on line 97
I searched all over the net for finding the right answers but some are just so complex to understand...
It supposed to be that $q2 is the variable inside an array. That variable is then multiplied to the "TOTAL". but the errors kept on going.. please help!!
The super-globals will always be strings. You need to explicitly convert them using intval():
$q2 = intval($_REQUEST['binge']);
Also, this line:
'book2'=>array...
Should be
$book2 = array...
You can use
$q2 = filter_var($_REQUEST['binge'], FILTER_VALIDATE_INT);
here you will have the benefit of validation where false is returned when someone passes a value that is not an integer. If it is instead a float use FILTER_VALIDATE_FLOAT instead.
Also, consider using $_GET, or $_POST directly to have more control of the data channel. $_REQUEST cobbles together several things into one, which sometimes may cause issues when more than one channel have the same key.

php get array elememnt using $$

i know this
$var1 = "10";
$var2 = "var1";
then
echo $$var2 gives us 10
i want to this with array
i have array
$intake_arr = array(5=>10,7=>20,8=>30,9=>40,10=>50,11=>60,12=>70);
i have some logic that will pick one array from set of array , all array will look like $intake_arr
if i do this $target_arr = "intake_arr";
then can $$target_arr[5] will yield 10? i tried but i didnt that 10 value, how can i achieve this with array
Your statement ($$target_arr[5]) is ambiguous. PHP doesn't know what you actually want to say: Do you mean: use $target_arr[5]'s value and prepend the $, to use that as a variable, or do you want to use the value of $target_arr, and get the fifth element of that array?
Obviously it's the latter, but PHP doesn't know that. In order to disambiguate your statement, you have to use curly braces:
${$target_arr}[5];
That'll yield 10. See the manual on variable variables for details
Note:
As people said in comments, and deleted answers: variable variables, like the one you're using is risky business. 9/10 it can, and indeed should be avoided. It makes your code harder to read, more error prone and, in combination with the those two major disadvantages, this is the killer: it makes your code incredibly hard to debug.
If this is just a technical exercise, consider this note a piece of friendly advice. If you've gotten this from some sort of tutorial/blog or other type of online resource: never visit that site again.
If you're actually working on a piece of code, and you've decided to tackle a specific problem using variable vars, then perhaps post your code on code-review, and let me know, I'll have a look and try to offer some constructive criticism to help you on your way, towards a better solution.
Since what you're actually trying to do is copying an array into another variable, then that's quite easy. PHP offers a variety of ways to do that:
Copy by assignment:
PHP copies arrays on assignment, by default, so that means that:
$someArray = range(1,10);//[1,2,3,4,5,6,7,8,9,10]
$foo = $someArray;
Assigns a copy of $someArray to the variable $foo:
echo $foo[0], ' === ', $someArray[0];//echoes 1 === 1
$foo[0] += 123;
echo $foo[0], ' != ', $someArray[0];//echoes 123 != 1
I can change the value of one of the array's elements without that affecting the original array, because it was copied.
There is a risk to this, as you start working with JSON encoded data, chances are that you'll end up with something like:
$obj = json_decode($string);
echo get_class($obj));//echoes stdClass, you have an object
Objects are, by default, passed and assigned by reference, which means that:
$obj = new stdClass;
$obj->some_property = 'foobar';
$foo = $obj;
$foo->some_property .= '2';
echo $obj->some_property;//echoes foobar2!
Change a property through $foo, and the $obj object will change, too. Simply because they both reference exactly the same object.
Slice the array:
A more common way for front-end developers (mainly, I think, stemming from a JS habbit) is to use array_slice, which guarantees to return a copy of the array. with the added perk that you can specify how many of the elements you'll be needing in your copy:
$someArray = range(1,100);//"large" array
$foo = array_slice($someArray, 0);//copy from index 0 to the end
$bar = array_slice($someArray, -10);//copy last 10 elements
$chunk = array_slice($someArray, 20, 4);//start at index 20, copy 4 elements
If you don't want to copy the array, but rather extract a section out of the original you can splice the array (as in split + slice):
$extract = array_splice($someArray, 0, 10);
echo count($someArray);//echoes 90
This removes the first 10 elements from the original array, and assigns them to $extract
Spend some time browsing the countless (well, about a hundred) array functions PHP offers.
${$target_arr}[5]
PHP: Variable variables
Try this one:
$intake_arr = array(5=>10,7=>20,8=>30,9=>40,10=>50,11=>60,12=>70);
$target_arr = 'intake_arr';
print ${$target_arr}[5]; //it gives 10
For a simple variable, braces are optional.But when you will use a array element, you must use braces; e.g.: ${$target_arr}[5];.As a standard, braces are used if variable interpolation is used, instead of concatenation.Generally variable interpolation is slow, but concatenation may also be slower if you have too many variables to concatenate.Take a look here for php variable variables http://php.net/manual/en/language.variables.variable.php

Adding increamental variable number to a variable

I am trying to create a loop that creates variables using the increment/count number:
$names = 4;
for($it=0;$it<$names;$it++){
$NAME{$it} = $_REQUEST['NAME'.$it.''];
$SURNAME{$it} = $_REQUEST['SURNAME'.$it.''];
$AGE{$it} = $_REQUEST['AGE'.$it.''];
}
My issue is that instead of getting $NAME0, $NAME1 etc, I am getting an array (so $NAME[0], $NAME[1] and so on).
How would I use the loop to get all the info in $NAME0, $NAME1, $NAME2, $SURNAME1, $SURNAME2 $SURNAME3, $AGE1, $AGE2, $AGE3?
Thanks :)
You don't want variables with related names; using an array is much simpler. In this case, $NAME0 is the same as $NAME[0], except you can do a lot more things with $NAME[0] than you can with $NAME0. Stick with the array, learn to use it; don't reinvent the wheel.
Generally speaking, this would be dangerous for super-globals (e.g. $_REQUEST) without serious forethought.
However, this is an excellent use case for the underused PHP function extract().
If you were to use it in such a case, I'd strongly recommend setting the additional parameters with the EXTR_PREFIX_ALL flag.
I agree with the others about using an array, much better but if that's not what you want, try adding an underscore to the variables... May not be "perfect" but won't create an array:
$names = 4;
for($it=0;$it<$items;$it++){
$NAME_{$it} = $_REQUEST['NAME'.$it.''];
$SURNAME_{$it} = $_REQUEST['SURNAME'.$it.''];
$AGE_{$it} = $_REQUEST['AGE'.$it.''];
}

How do I get the name of a variable variable?

So, I need the actual variable name "varName" from global space. This function is actually a method inside a class.
Code is arbitrary for simplicity
$varName = 'what ever';
public function save($var)
{
$i[varName goes here] = $var;
}
I don't know if this is even possible, but I think maybe with a callback?
If it's a global variable, you might be able to find out the original name with:
$varname = array_search($var, $GLOBALS);
But that's not overly reliable; a best guess. If two global variables would contain the same value, you would just receive the name of either of them.
Read about $GLOBALS variable in the documentation.
This is probably what you need. Depending on the way you determine which variable you need, you can for example user array_search() to find the proper name based on the value.
Caution: $GLOBALS is about global scope's variables.
EDIT:
But this would be still a guess. You may try the following method to determine the name of the passed variable with ~100% certainty:
Pass variable to the method with reference.
Use array_search() for finding the name of the variable. If only one key matches it, you have your name. If not, go to the next step.
Save the initial value of the variable and save the list of positions at which you have found matching elements.
Change the variable's value into new one. Perform another search based on new value and get positions that are also in the list of positions from point no. 3.
At this point you have probably found the name of the variable you are looking for.
But...
Is it really needed? I suggest that you should look for simpler solution, some better encapsulation of your code.
Ps. array_search() actually returns no more than one key (see documentation). You should know that and make searching for multiple results a little more sophisticated to not skip the correct one if more than one variable matches your search criteria. (EDIT2: As mario suggested, array_intersect($GLOBALS, array($var)) will suffice)
In C, you would use a macro. I don't think there's an equivalent in PHP.
You could pass the name of the variable to the function as a string, then in the function get the variable's value from GLOBALS or eval it.
Thanks for the solution!
Here is my test:
<?php
$varName = 'what ever';
function save($var)
{
$i[array_search($var, $GLOBALS)] = $var;
print_r($i);
}
save($varName);
?>
prints:
Array
(
[varName] => what ever
)

Categories