1

I recently tried to create an array with multiple Strings, representing the AcceptLanguage header. I need to push another user-specified language to the start of the array, to make it max priority.

So far I have

function getRequestLangs(){
    //get languages from browser
    $accLangs = explode(',',$_SERVER['HTTP_ACCEPT_LANGUAGE']);

    $requestedLanguages = array();
    foreach($accLangs as $key => $lang){

        $lang = substr($lang,0,2);
        // p is a quality param, we won't need it, since the
        // preferred languages are already sorted by default 
        if($lang != 'p='){
            array_push($requestedLanguages,$lang);
        }
    }
    // we only need each language once, this function keeps the order
    return array_unique($requestedLanguages);
}

Now I want to add the user-specified language as first key (in case the language is not supportet, I may fall back to another accepted language)

//language from path, pushed as first index (highest priority)
if(isset($_GET['lang']) && $_GET['lang'] != ""){
        $requestedLanguages = array_unshift($requestedLanguages,$_GET['lang']);
}

var_dump($requestedLanguages) before array_unshift:

    array(2) { 
         [0]=> string(2) "de" 
         [2]=> string(2) "en" 
    } 

var_dump($requestedLanguages) after array_unshift:

    int(3) 

I think it might have to do with the index-hole between 0 and 2, but that is only a guess.

[EDIT] i need more caffeine...

//wrong:
$requestedLanguages = array_unshift($requestedLanguages,$_GET['lang']);

//right:
array_unshift($requestedLanguages,$_GET['lang']);
2
  • 5
    read the manual... Returns the new number of elements in the array. Commented Aug 9, 2013 at 7:50
  • yes. i saw that like 30 seconds after i postet this question... Commented Aug 9, 2013 at 8:02

1 Answer 1

3

array_unshift mutates the supplied array and returns the new number of elements in the array after the item was prepended to it, so the int(3) is telling you that there are now three items in the array.

https://www.php.net/manual/en/function.array-unshift.php

Sign up to request clarification or add additional context in comments.

2 Comments

Maybe you should accept this answer if it answers your question :-)
yea, i wanted to do that, but it gave me "you may accept it in 3 minutes"

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.