Solution 1 :

You can add if statement as ternary operator before $data:

$Link = $language[7] !== 'en' ? 
         $baseURL . $language[2] . '/' . $activeLink : 
         $baseURL . $activeLink; 

$data .= '<link rel="alternate" 
                hreflang="' . $language[7] . '" 
                href="' . $Link . '" />
' . PHP_EOL;

This row a little bit hard to understand:

href="' . $baseURL . $language[2] . '/' . $activeLink . '"

Seems like $language[2] equal to en as it also equal to $language[7]. So, in case of $lang[7] = 'en' you don’t need to use . $lang[2] . '/' which seems to be equal to en/. About $activeLink I can’t say anything. Seems like it’s not the key value with which I should have a deal.

Problem :

function genCanonicalData($baseURL, $currentLink, $loadedLanguages=array(), $return = false, $langSwitch=true){
    $data = $activeLang = $activeLangSlash = '';
        $activeLangSlash = ACTIVE_LANG.'/';
        $activeLang = ACTIVE_LANG;

    $activeLink = str_replace(array($baseURL.$activeLangSlash, $baseURL.$activeLang, $baseURL), '', $currentLink);

    $data .= '<link rel="canonical" href="'.$currentLink.'" />'.PHP_EOL;

    if($langSwitch) {
        foreach ($loadedLanguages as $language) {
            if (!isset($language[7]))
                $language[7] = $language[2];
            elseif ($language[7] === NULL)
                $language[7] = $language[2];
            $data .= '        <link rel="alternate" hreflang="' . $language[7] . '" href="' . $baseURL . $language[2] . '/' . $activeLink . '" />' . PHP_EOL;
        return $data;
        echo $data;

Above is the code that I is used to Generate Hreflang tag for all available language. In My Site there are 7 Language Including English and English is the Default Language. While Above Code Gives the result this

<link rel="canonical" href="" />
<link rel="alternate" hreflang="en" href="" />
<link rel="alternate" hreflang="ar" href="" />
<link rel="alternate" hreflang="de" href="" />
<link rel="alternate" hreflang="es" href="" />
<link rel="alternate" hreflang="fr" href="" />
<link rel="alternate" hreflang="it" href="" />
<link rel="alternate" hreflang="pt" href="" />

But I Didn’t Want /en for hreflang=”en” because English is the default. How Can I Do This?


Comment posted by mickmackusa

Please complete your question by providing sample data, how you call your function, and your exact desired output from your sample data — this makes your question completely clear and the answers you receive will be verifiable.

Comment posted by Vishal Gupta

I’m also Not Talking about

Comment posted by Aksen P

@VishalGupta, I got it, thnx. Have you tried to add

Comment posted by Vishal Gupta

Not Yet but I’m going to add as you told then I will reply. Thank You