Reputation: 21
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?
Upvotes: 0
Views: 73
Reputation: 5896
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
Upvotes: 3
Reputation: 21
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.
Upvotes: 0
Reputation: 1272
$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.
Upvotes: 0
Reputation: 39451
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.
Upvotes: 1