How to get WordPress Permalink to a variable

I think you already know we can’t use the_permalink() function to assign WordPress permalink to a PHP Variable, because it is echo the permalink instead of returning. So how we can get the post URL to a PHP Variable ?

get_permalink function use to retrieve the permalink of current post or given post id (Also works for WordPress Pages).

<?php echo $post_url=get_permalink(); ?>

By default without argument get_permalink function returns the url of the current post. If you want to get the url of another post , pass the post id or page id as an argument.

<?php echo $post_url=get_permalink(id); ?>

get_permalink function works for both WordPress post and WordPress pages. And can be used both inside and outside of the post loop.