First of all, to make sure that you understand this, because I see a lot of beginners stumbling over the difference between server side scripting and client side scripting, javascript is a client side scripting language, while PHP is server side. If you understand this, you can basically skip this paragraph. When the user requests a page, such as mysite.com/whatever.php, the request gets sent to the server. Because the user requests the PHP file, the server knows that it should parse the file before sending it to the user. When parsing a file, the server starts n HTML mode, which means that all the text it reads is going directly to the user. From the moment php encounters a or the end of the file. When the end of the file is reached, it sends the output to the user. This output may contain script tags in it's HTML. These peaces of javascript will be executed when they are red together with the HTML by the browser.
However, an external javascript file, doesn't need to have the .js extension, just like css. Therefore, you can also make a php file that outputs js, and do as one of the previous answers suggested, so to put this js code in a .php file:
var somevar = <?php echo $var; ?>;
as you can see, after the equals sign in the javascript, the php variable $var 's value will be printed. This value will therefore be assigned to the js variable called somevar when the output is red by the browser.