0

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?

2
  • I see two things, first you are not passing $parts to your function. Then array_unsift, doesn't returns a new array, but the number of new elements, so should not assign the $parts from array_unshift. Commented Dec 5, 2018 at 21:57
  • I added $parts as a parameter, but still doesn't help. Maybe I am thinking too much JS-like? Commented Dec 5, 2018 at 21:59

2 Answers 2

3

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);
Sign up to request clarification or add additional context in comments.

1 Comment

Yes this is working like a charm. Thank you. I haven't coded for a while and I learned to code through JS. Perhaps my experience reflects in my PHP coding style.
-1

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

2 Comments

Thanks for your answer but it didn't help
Global keyword is generally considered bad practice. edit: not my DV

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.