loops - PHP for each for items in array with Drupal -


i trying calculate value based on price field in entity reference field.

i have this, works...

if (isset($entity->field_choose_a_package['und'][0]['target_id'])) {     $package1nid = $entity->field_choose_a_package['und'][0]['target_id'];     $package1 = node_load($package1nid);     $package1price = $package1->field_price['und'][0]['value']; } else {     $package1price = 0; }  if (isset($entity->field_choose_a_package['und'][1]['target_id'])) {     $package2nid = $entity->field_choose_a_package['und'][1]['target_id'];     $package2 = node_load($package2nid);     $package2price = $package2->field_price['und'][0]['value']; } else {     $package2price = 0; }  if (isset($entity->field_choose_a_package['und'][2]['target_id'])) {     $package3nid = $entity->field_choose_a_package['und'][2]['target_id'];     $package3 = node_load($package3nid);     $package3price = $package3->field_price['und'][0]['value']; } else {     $package3price = 0; }  $packagestotal = $package1price + $package2price + $package3price;  $entity_field[0]['value'] = $packagestotal; 

however, there unlimited amount of packages added, , rather me replicate code 20+ packages try , cover bases, there must way can each loop.

i have tried this,

$arr = $entity->field_choose_a_package['und'];  foreach ($arr &$value) {     if (isset($entity->field_choose_a_package['und'][$value]['target_id'])) {         $package1nid = $entity->field_choose_a_package['und'][$value]['target_id'];         $package1 = node_load($package1nid);         $package1price = $package1->field_price['und'][$value]['value'];     } else {         $package1price = 0;     } }  unset($value); 

but cant figure out how increment variables, or if need to? can calculate totals foreach?

$packagestotal = 0; $numpackages = 3;  for($i = 0; $i <= $numpackages; $i++) {     if(isset($entity->field_choose_a_package['und'][$i]['target_id'])) {       ${'package' . $i . 'nid'} = $entity->field_choose_a_package['und'][$i]['target_id'];       ${'package' . $i} = node_load(${'package' . $i . 'nid'});       $packagestotal += ${'package' . $i}->field_price['und'][0]['value'];     } }  $entity_field[0]['value'] = $packagestotal; 

that should work.

although, recommend wrap package variables in array rather using variable variables code more readable , access each package attribute using $package[$i]


Comments