0

I have two arrays. one will be added with arrays as children, another one keeps references to the array being added to the first one.

$list=array();
$stack=array();

in a for loop:

$list[]=array('something');
$stack[]=& end($list); //errors: Only variables should be assigned by reference 

what am i doing wrong here? thanks for help.

2
  • The error message seems pretty self-explanatory. And why the new Array? Just Array will do. Commented Jul 9, 2011 at 18:16
  • @tomalak, sorry, that was a mistake.. Commented Jul 9, 2011 at 18:17

2 Answers 2

1

Edited

$stack[] = &$list[count($list)-1];  //> Assuming numeric index incremental

or

end($list);
$stack[] = &$list[key($list)];
Sign up to request clarification or add additional context in comments.

8 Comments

this way, the reference is to $var, not to end($list) ?? right?? I want the reference to the end($list), so it will not disppare outside the for loop.
&= means something different. Probably not what's intended.
Still it won't be a reference to the last element of $list but to the new variable $var.
@Gedrox Taken from the documentation: "The same syntax can be used with functions that return references, and with the new operator".
The problem is that in the first line the reference is lost. The function "end" returns the copy of the last element from the array.
|
0

Objects will be always passed by reference in PHP 5.

EDITED

But if array is not a class then

$element = array();
$list[] = &$element;
$stack[] = &$element;

3 Comments

sorry, I am a beginner in php. so does the same to arrays??
The code is ment if you work with PHP arrays. Of course you need to pass filled array into the $element.
so both list and stack are arrays of reference to $element??

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.