Does the PHP function current () return a copy or array reference?

I created a simple test case that replicates the problem I have.

I am going through a two-dimensional array using the next() and current() functions, and I want to set the array pointer to a specific location. So, given a 2D array with the variable name $food with the following array structure:

 array 0 => <-- POINTER LOCATION array 0 => string 'apple' <-- POINTER LOCATION 1 => string 'orange' 1 => array 0 => string 'onion' 1 => string 'carrot' 

... and the following piece of code:

 // move the inner array pointer once $should_be_orange = next(current($food)); // now check that inner array value $should_still_be_orange = current(current($food)); 

... Why is the value of $should_be_orange "orange", but the value of $should_still_be_orange "apple"? Is this because the current() function returns a copy of the internal array, which the pointer gets iterated and then destroyed (leaving the original array intact)? Or am I just doing something wrong that I will not catch?

At the root of the question, how do you move the pointer of an internal array, given that you do not know the key of the external array (and should use the current() function to get the location of the pointer of the external array)?

+4
source share
2 answers

In fact, current() returns an element from an array. In your case, this element is also an array, and so next() works in general in your code. Your next() does not work in the $food array, but on the copy of $food[0] returned by current()

+2
source

The function cannot pass arguments to arguments, you can only variables because the argument refers:

 function current(&$array) {...} function next(&$array) {...} 

therefore the correct syntax is:

 // move the inner array pointer once $tmp = current($food); $should_be_orange = next($tmp); // now check that inner array value $tmp = current($food); $should_still_be_orange = current($tmp); ^^^^^^ NO! It should be "apple" ! When you do next($tmp) it will be orange ! 

Demo: http://codepad.viper-7.com/YZfEAw

Documentation:


When you are learning PHP, you should display ALL errors with the command:

 error_reporting(E_ALL); 

Using this, you should receive a notification:

 Strict Standards: Only variables should be passed by reference in (...) on line (...) 

(I think this answer needs to consider the reasons for English grammar)

+1
source

Source: https://habr.com/ru/post/1381380/


All Articles