Richard Housham
Richard Housham

Reputation: 864

Does anyone know why this php iteration won't work

Does anyone know why this doesn't work

function my_current($array) {
    return current($array);
}

$array = array(1,3,5,7,13);

while($i = my_current($array)) {
    $content .= $i.',';
    next($array);
}

yet this does

$array = array(1,3,5,7,13);

while($i = current($array)) {
    $content .= $i.',';
    next($array);
}

or how to make the top one work? It's a little question but it would be a big help! Thanks Richard

Upvotes: 0

Views: 89

Answers (3)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799430

The array is copied, which means that the current pointer is lost. Pass it as a reference.

function my_current(&$array) {

Or better yet, use implode().

Upvotes: 3

svens
svens

Reputation: 11628

I guess it's because when you call a function with an array parameter, the array is copied over. Try using references.

function my_current(&$array) {
    return current($array);
}

Notice the &.

Upvotes: 2

Evert
Evert

Reputation: 99816

By default a copy of the array is being made.

Try this:

function my_current(&$array) {
    return current($array);
}

Upvotes: 2

Related Questions