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?

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

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.