0

I would like to use php variable in my javascript. This is what I currently have and is working just fine:

<?php 
$test = '"test1","test2",test3"';
?>
<script type="text/javascript">
var values = [<?php echo $test; ?>],
valueToUse = values[Math.floor(Math.random() * values.length)];
alert(valueToUse);
</script>

However, if I use values that are retrieved from a database, this code will not work. Both variables contain exactly same values and are string type.

  • Why don't you just use PHP's `rand()`? – Nijraj Gelani Mar 01 '16 at 06:14
  • What does your JS look like after rendering the PHP code? What JS errors are you getting? – B-and-P Mar 01 '16 at 06:14
  • The snippet is lacking a quotation for `test3` and should result in a syntax error in JavaScript. Also, to help avoid typos like that, consider using `$test = array('test1', 'test2', 'test3');` and `var values = ;`. ([How to pass variables and data from PHP to JavaScript?](http://stackoverflow.com/questions/23740548/how-to-pass-variables-and-data-from-php-to-javascript)) – Jonathan Lonowski Mar 01 '16 at 06:17
  • It's a string because your php variable your giving to it is a string. So your resulting values array will always be [string] at which point your random number generates a number between 0 and 1 then floors it which means except for the very very rare chance you get a 1 it grabs your array at value 0 which is the only value your string. – Binvention Mar 01 '16 at 06:53
  • U can't use JS with PHP dude – Abrar Jahin Mar 01 '16 at 07:19

1 Answers1

0
<?php 
$test = 'test1,test2,test3';
?>
<script type="text/javascript">
var values = <?php echo $test; ?>;
values=values.split(",");
valueToUse = values[Math.floor(Math.random() * values.length)];
alert(valueToUse);
</script>

Your problem was your test variable was a sting however if you call the JavaScript split function on a string it easily turns a , separated list into a JavaScript array

Binvention
  • 1,057
  • 1
  • 8
  • 24