0

While you can pass a PHP array to a JavaScript function, can you pass the opposite? (a JavaScript function into an PHP array).

Consider this code. I want to call a JavaScript timer inside a PHP array, as the array later randomizes messages for an echo.

$messages = array('How are you today?', 'Perfect day for flying, isnt it?', 'You have flown last on '.$lastflown.'.', 'The time is /* insert the JavaScript function to call a timer here */');
$key = array_rand($messages);

And of course I want to display the message:

<?php echo $messages[$key]; ?>

Is this possible? If not, how can this be bypassed? Perhaps a JavaScript randomizer instead?

Community
  • 1
  • 1
zzwyb89
  • 472
  • 1
  • 7
  • 21
  • 1
    *"Perhaps a JavaScript randomizer instead?"* yes I highly recommend to read http://stackoverflow.com/q/13840429/218196 to get a better understanding of how PHP and JavaScript interrelate. – Felix Kling Oct 21 '15 at 13:40
  • No you can't, like Felix say, php is server side. And the javascript is executed on browser, not on server. – Alaanor Oct 21 '15 at 14:06

1 Answers1

1

Maybe this code help you.

$messages = array('How are you today?', 'Perfect day for flying, isnt it?', 'You have flown last on '.$lastflown.'.', 'The time is <script> document.write(new Date().toString());</script>');
$key = array_rand($messages);

<?php echo $messages[$key]; ?>

You need surround your JavaScript code with tags. To show JavaScript output use document.write() function.

This string 'The time is <script> document.write(new Date().toString());</script>' will be show like The time is Wed Oct 21 2015 17:18:32 GMT+0300 (MSK) in browser.

DLevsha
  • 136
  • 3