I’m trying to pass some variables from PHP to JS.
I saw here that for strings the following code would work:
var str = "<?php echo $x; ?>";
I’ve been using this:
var var1 = <?= $var1 ?>;
Which one should I use for int? the first version is always good? Is the second one just an old form? I’d be happy for a clarification and instruction on passing variables (dif types) from php to js in general.
Thanks!
First of all, lets go over how to declare a variable in javascript.
There are many types of variables, but lets go over
intandstring. Strings have to have quotation marks around the.Int‘s don’t.Now when we are passing a variable from php to javascript, all we are doing is replacing the value after the equal sign with a variable declared in php. You mentioned the two ways for echoing a variable.
If these variables were
int(which by the way includes any number, whether integer or not), there would be no quotation marks around the php open and close tags. Now, you said you prefer using the second method. I would really advise you not to. Even though it is a lot easier to type<?= $phpVariable ?>than<?php echo $phpVariable; ?>, the former one isn’t supported on all servers, whereas the latter one is. You can use it if you want, but if you ever want to move to a server, you need to check if that syntex is allowed first.