1

I have a function using array_search not working ... here is my code

function LangFull($name){
    $languageCodes = array(
"abkhazian"=>"ab",
"afar"=>"aa",
"afrikaans"=>"af",
"afrikaans"=>"af-za",
"zulu"=>"zu",
"zulu"=>"zu-za"
    );
    return ucwords(array_search(strtolower($name),$languageCodes));
}

echo LangFull("zu"); /// Gives no output
echo LangFull("zu-za"); /// Gives output

same with af is no output ... please help

2
  • "zulu"=>"zu", "zulu"=>"zu-za" array keys must be unique, print_r($languageCodes) inside the function and you'll know whats up Commented Mar 13, 2015 at 4:14
  • Thx for reply 😃 if I change value to key and key to value how can I get key as output ... In same array_search Commented Mar 13, 2015 at 4:22

2 Answers 2

1

If its possible to interchange, (values to keys and keys to values) and won't have those key collisions, then you can do it that way also:

function LangFull($name){
    $languageCodes = array(
        "ab" => "abkhazian",
        "aa" => "afar",
        "af" => "afrikaans",
        "af-za" => "afrikaans",
        "zu" => "zulu",
        "zu-za" => "zulu",
    );
    return isset($languageCodes[$name]) ? ucwords(strtolower($languageCodes[$name])) : 'Not found';
}

echo LangFull("zu"); /// Gives output
echo LangFull("zu-za"); /// Gives output
echo LangFull("yahoo!");
Sign up to request clarification or add additional context in comments.

Comments

1

You have two identical array keys:

"zulu"=>"zu",
"zulu"=>"zu-za"

You need to name one of them something else.

As they are the same, trying to access one of them specifically is futile as PHP does not know which of the two you are requesting.

Alternatively, if you are trying to store more than 1 data value for a given key, you can make the value of a key an array, so can then store more data as required.

e.g.

array (
  "afrikaans"=> array(
     "af",
     "af-za",
  ),
  "zulu"=> array(
     "zu",
     "zu-za",
  )
);

EDIT.
In response to you asking about swapping the keys and values:
You can, and Ghost has shown you how.
However retaining your keys as they are (as my above array example) allows you to collate all relevant data into one index, and can access it easily.

Swapping values and keys will likely make it harder to obtain data you need, as your key is now the "data". So to grab data from an array you'd need to know the data (as it's now the key) and you'd actually be grabbing the reference (what was your key).

Which is a bit odd. It can work, but it's not really ideal.

1 Comment

Thx for reply 😃 if I change value to key and key to value how can I get key as output ... In same array_search thx

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.