mardi 18 octobre 2016

If elseif condition inside foreach with array

I'm using a if elseif condition inside the foreach loop. Inside both if and elseif two different functions are calling and retrieving value to same array $nice[]. If I run the following code, only the if condition is working.

$youtube = array(
             'https://www.youtube.com/watch?v=nCwRJUg3tcQ1&list=PLv5BUbwWA5RYaM6E-QiE8WxoKwyBnozV2&index=4',
             'http://ift.tt/2eMwQo3',
             'http://www.youtube.com/watch?v=nCwRJUg3tcQ2&feature=relate',
             'http://youtube.com/v/nCwRJUg3tcQ3?feature=youtube_gdata_player');  

$nice = array();  

foreach ($youtube as $url) {
if(preg_grep("/youtu/i", $youtube)){
    $nice[] = getYoutubeId($url);
}elseif(preg_grep("/vimeo/i", $youtube)){
    $nice[] = getVimeoId($url);}
}  

print_r($nice);  

function getVimeoId($url)
{
    if (preg_match('#(?:https?://)?(?:www.)?(?:player.)?http://ift.tt/2egCAUo', $url, $m)) {
        return 'v_'.$m[1];
    }
    return false;
}  

function getYoutubeId($url)
{
    $parts = parse_url($url);
    if (isset($parts['host'])) {
        $host = $parts['host'];
        if (false === strpos($host, 'youtube') &&
            false === strpos($host, 'youtu.be')
            ) 
        {
            return false;
        }
    }
    if (isset($parts['query'])) {
        parse_str($parts['query'], $qs);
        if (isset($qs['v'])) {
            return 'y_'.$qs['v'];
        }
        else if (isset($qs['vi'])) {
            return 'y_'.$qs['vi'];
        }
    }
    if (isset($parts['path'])) {
        $path = explode('/', trim($parts['path'], '/'));
        return 'y_'.$path[count($path) - 1];
    }
    return false;
}

The current output is:

Array ( [0] => y_nCwRJUg3tcQ1 [1] => [2] => y_nCwRJUg3tcQ2 [3] => y_nCwRJUg3tcQ3 )

There is no value in [1] position.

Aucun commentaire:

Enregistrer un commentaire