Page 1 of 1

Passing reference to array in "foreach" produces error

Posted: Thu Sep 25, 2008 11:01 am
by loutka
Hello,
I'm trying to access array through foreach and change values for particular key.

I'm able to access array without reference, but when I add & to create reference I receive:
Parse error: syntax error, unexpected '&', expecting T_VARIABLE or '$' in /home/.../modules/taxonomy_menu/taxonomy_menu.inc on line 185
My code:

Code: Select all

 
<?php
foreach ($items as &$menu_item){       
    $menu_item['path'] = drupal_get_path_alias( 'taxonomy/term/' . end(explode('/',$menu_item['path'])) );               
  }
unset ($menu_item);
?>
 
Regarding to http://uk3.php.net/foreach this should work:

Code: Select all

 
<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 8)
unset($value); // break the reference with the last element
?>
 
I'm really confused and can't figure it out... ???

Any way around? Can I access array value directly (from within fereach) and change it?

Could anyone help me please?
Thanks!

Re: Passing reference to array in "foreach" produces error

Posted: Thu Sep 25, 2008 2:00 pm
by Darkzaelus

Code: Select all

 
foreach ($arr as $key => $value) {
    $value = $value * 2;
}
 
Using & passes a reference. As you have no variable called $value, it will throw an error.


Cheers,

Darkzaelus.

Re: Passing reference to array in "foreach" produces error

Posted: Thu Sep 25, 2008 6:44 pm
by Stryks
Actually ... at first glance that reference method should work. I've used it like that before.

Anyhow, as a workaround ...

Code: Select all

foreach($items as $key=>$menu_item) {
   $items[$key]['path'] = drupal_get_path_alias( 'taxonomy/term/' . end(explode('/',$menu_item['path'])) );
}
... or ... something like that. Cant test it here, so cant be more positive of the outcome.

Cheers

Re: Passing reference to array in "foreach" produces error

Posted: Thu Sep 25, 2008 6:47 pm
by Stryks
Also, just note that the reference method only works with PHP 5 and later.

Perhaps you are running a previous version of PHP?

Re: Passing reference to array in "foreach" produces error

Posted: Fri Sep 26, 2008 3:34 am
by loutka
Thank you guys!

All solved now...

My hosting provider claims our PHP version is 5, but phpinfo() says PHP version 4.2.6.
- that's why referencing didn't work

So I've used way around by using key.

Re: Passing reference to array in "foreach" produces error

Posted: Fri Sep 26, 2008 6:16 am
by VladSun
loutka wrote:My hosting provider claims our PHP version is 5, but phpinfo() says PHP version 4.2.6.
Try to rename your files from *.php to *.php5 ;)