Question

I am trying to create a dynamic link, in this way:

  • Take an array
  • Search for the key of one element
  • Delete this element
  • Implode the array elements to a string
  • Show the string as a parameter in the link

I am doing it like it follows:

 $url_langs=array('fra','cat','hun'...); //CURRENT LANGS in use

 $all_langs=array('eng','fra','por','ser','cat','dan','hun','fin','est','esl',...);

 foreach($all_langs as $lang){
    echo (in_array($lang,$url_langs))?'<a href="' . implode('|',unset($url_langs[array_search($lang,$url_langs)])) . '">' . $lang . '</b> ':'<a href="' . implode('|',$url_langs) . '|' . $lang . '">' . $lang . '</a> ';
 }

Well, as you can see. I iterate the array which contains all the available languages, and check if it is already in use or not. If it is in use, I show a link to not use it; and the same for the contrary case.

As the php manual (unset) says: "No value is returned.". So I can't use unset on the fly. My questions are:

  1. Is there any alternative form to achieve it?
  2. I could use the long if sentence, and define a new array which I will then use for the implode() function. But, isn't it strange? Crate a new array if my goal is make it as plain text?
  3. I could use a str_replace to remove this part of the string once imploded... but this I can't do it on the fly, neither.

Thanks a lot.

Was it helpful?

Solution

array_diff(a1, a2) will return an array of a1 values which are not in a2. So converting $lang to an array value as array($lang) and taking array difference will give you the desired values

You are also missing an </a> at the first <a href=

$url_langs=array('fra','cat','hun'...); //CURRENT LANGS in use
$all_langs=array('eng','fra','por','ser','cat','dan','hun','fin','est','esl',...);
foreach($all_langs as $lang){
    echo (in_array($lang,$url_langs)) ? 
          '<a href="' 
         . implode('|',array_diff($url_langs, array($lang))) 
         . '">' . $lang . '</a></b> '     :
          '<a href="' 
         . implode('|',$url_langs) . '|' . $lang . '">' . $lang . '</a> ';
}

OTHER TIPS

I would use array_diff in your case:

$new_langs = array_diff($all_langs, $url_langs);
print_r($new_langs);
// this will print
// Array([0] => eng [2] => por [3] => ser [5] => dan [7] => fin [8] => est [9] => esl)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top