PHP7 + JavaScript, 62 61 58 bytes
This was actually more challenging than I expected! I am quite surprised of how long my code is.
eval(['alert((_=prompt())*_)','echo$argv[1]**.5'][+![]]);
How does it work?
This works by selecting the code to run, from the array.
PHP and JavaScript detection is made with +![]
.
In PHP, []
(empty array) is a falsy value, while in JavaScript it is a truthy value (objects (except null
) are always truthy, even new Boolean(false)
is truthy!).
But, I need to get it to a numeric value, so, I just use a not
(!
) and convert it to integer (with the +
).
Now, PHP yields the value 1
, while JavaScript yields 0
.
Placing the code inside an array, at those indexes, will allow us to select the right code for the desired language.
This can be used as [JS,PHP][+![]]
, to get the code of the right language.
On previous polyglots, I've used '\0'=="\0"
, which is true
in JavaScript (since \0
is parsed as the NULL-byte) and false
in PHP (the '\0'
won't be parsed as the NULL-byte, comparing the literal string \0
with the NULL-byte).
I'm happy that I've managed to reduce this check to +!'0'
.
I'm even more happy about @rckd, which reduced it to the current version!
From there on, it simply eval
s the code required.
PHP
PHP will execute echo$argv[1]**.5
(equivalent to echo sqrt($argv[1]);
, square-root the number), receiving the value from the 2nd argument and displays it in the standard output.
JavaScript
JavaScript executes alert((_=prompt())*_)
, which displays the squared number in an alert
.
Thank you to @rckd for saving 1 byte, and @user59178 for saving 3 bytes!