Post tags show outside loop?

The code is tested and working fine.

Place this code

<?php
    $posttags = get_the_tags();

    if( ! empty( $posttags ) ) :
        $tags = array();

        foreach($posttags as $key => $value){
            $tags[] = $value->name;
        }

?>

    <meta name="keywords" content="<?php echo implode( ',', $tags ); ?>,test"/>

<?php endif;?>

instead of

<meta name="keywords" content="<?php the_tags( '', ',', '' );?>test<?php }?>"/>