Jump to content

Passing reference to array in "foreach" produce error


loutka

Recommended Posts

Hi guys!

 

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:

<?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:

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as &$value) {
    $value = $value * 2;
}
// $arr is now array(2, 4, 6, 
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!

You could just do this:

 

<?php
$arr = array(1, 2, 3, 4);
foreach ($arr as $k=>$value) {
    $arr[$k] = $value * 2;
}
// $arr is now array(2, 4, 6, 
unset($value); // break the reference with the last element
?>

 

I'm using an array within an array and need to change all values with particular key ($menu_item['path']) in the inner array.

Does it make sense to you?

 

Odd, use phpinfo() to verify it's executing with PHP5

 

<pre><?php

$array = array( 'foo', 'bar', 'hello', 'world' );

foreach( $array as &$val ) {
$val .= ' modified';
}
unset( $val );

print_r( $array );

?></pre>

 

Outputs

 

Array
(
    [0] => foo modified
    [1] => bar modified
    [2] => hello modified
    [3] => world modified
)

 

for me. PHP 5.2.6, Apache 2.2.8

Thank you all guys, really appreceate! It is working now...

 

Thank you kenrbnsn:

My fault, I've checked it just in cPanel

 

Thank you F1FAN:

Of course I used it this way many times... I think I had one of those days when you look in your code and nothing works ;)

 

Thank you DISCOMATT:

phpinfo() => PHP Version 4.4.9

But hosting provider claims we have PHP 5.2.6 installed... Grrr!

 

 

 

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.