Marco V
Marco V

Reputation: 2653

PHP array_unshift not working within function

Here is the preceding part of the code that returns an array containing either 4 or 5 indexes:

$page = icl_object_id(2880, 'page', true);
$url = get_permalink($page);
$parts = explode("/", $url);

I created a function that counts the amount of indexes in the array. The idea behind this is to artificially inflate the array with 1 index in case the total is 4.

function partsSumcheck() {
    if (count($parts) === 5) {
        return $parts;
    } else {
        $parts = array_unshift($parts, 'filler');
        return $parts;
    };
}
partsSumcheck();
var_dump($parts);

However, when the array returns with 4 indexes, I do an var_dump on $parts, and the array still has 4 indexes, even after the unshifting. Why?

Upvotes: 0

Views: 509

Answers (2)

Tyler Marien
Tyler Marien

Reputation: 762

array_unshift returns the number of new elements in the array, not the new array. Plus you should pass in the array and re-assign it after it returns.

function partsSumcheck($parts) {
    if (count($parts) === 5) {
        return $parts;
    } else {
        array_unshift($parts, 'filler');
        return $parts;
    };
}
$parts = partsSumcheck($parts);

Upvotes: 3

Ondřej Doněk
Ondřej Doněk

Reputation: 529

You should add global $parts on top of the function body.

Upvotes: -1

Related Questions