0

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?

1
  • 1
    Ellaborate on "not working"... Commented Dec 16, 2012 at 4:34

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0
$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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.