onassar
onassar

Reputation: 3558

why is php complaining about passing by reference in this code?

$test = 'love';
$eff = end(explode('ov',$test));

I can't figure it out; oddly enough, this doesn't get a complain:

$test = 'love';
$eff = current(explode('ov',$test));

The error I'm getting is: Strict: Only variables should be passed by reference

Upvotes: 0

Views: 181

Answers (4)

Ollie Saunders
Ollie Saunders

Reputation: 8057

end() modifies the array passed to it, by reference. Assign the explosion to a variable first so that end() has a reference it can modify.

$test = 'love';
$explosion = explode('ov',$test);
$eff = end($explosion);

end() only changes an internal pointer so it doesn't modify the contents of the array in anyway and you won't notice unless you're using the current(), each(), next() lot for iteration.

If this limitation of end() is annoying to you there are ways around it:

function last($array) { return end($array); }
$test = 'love';
$eff = last(explode('ov', $test));

Upvotes: 2

mauris
mauris

Reputation: 43619

<?php

error_reporting(E_STRICT);

$test = 'love';
$eff = end(explode('ov',$test));
var_dump($eff);

?>

it will work fine if your error reporting level is not set to E_STRICT.

See, when you have an temporary array returned, you cannot just set the internal pointer just like this. You need to set it to a variable first then move the internal pointer to the end using end().

This is true so for: reset(), next(), prev() and so on.

The following would work instead.

<?php

error_reporting(E_STRICT);

$test = 'love';
$a = explode('ov',$test);
$eff = end($a);
var_dump($eff);

?>

current() works because it does not move the internal pointer, but to get what the current element that the internal pointer is pointing at.

Upvotes: 0

strager
strager

Reputation: 90012

end changes the array's internal pointer by moving it to the end of the array. Thus, the parameter must be mutable (that is, a reference to an array) for that operation to be useful. This is why you receive the warning.

current doesn't touch the array at all; it only looks at the array. Thus, the parameter does not need to be mutable (thus can be passed by value) and the operation doesn't give you a warning.

Upvotes: 5

p00ya
p00ya

Reputation: 3709

The explode returns a temporary array, which you are not 'storing' to a variable but rather passing directly to end which expects a reference.

I believe the reason why current does not trigger the error is that it is non-mutating. Other mutating functions such as array_unshift and reset complain too.

Upvotes: 2

Related Questions