views:

59

answers:

4

I have thos piece of code:

Math&&Math.random?Math.floor(Math.random()*10000000000000):Date.getTime();

And as far as i know && is logic operator for AND, so im trying to convert this into PHP and this is where i got:

intval(floor(time()/10800000)%10+(rand()?floor(rand()*10000000000000):time()))

The problem is that i can't understand the first part

Math&&

Can anyone help with this one cause i always get negative result, when i should get positive (probably the logic rand-time is not working in my php example)

+3  A: 

That's a test to make sure the Math class is available in the browser. You don't need that in PHP. The second clause checks to make sure the Math.random method is available. It uses it if it is, and uses the time if it is not.

In PHP, just use rand(). http://us2.php.net/rand

Scott Saunders
That's what it looks like… Although it's useless, because `blah` will raise an undefined error if no `blah` is defined (ie, it won't return `undefined`)
David Wolever
Thanks now that seems to make sense
Anonymous
One last problem: converted to php sometimes this generates negative numbers, while in jS they are always positive?
Anonymous
rand() in php will never give you a negative number. If you need to limit the range, you can give it minimum and maximum values like this: $value = rand(1, 1000);
Scott Saunders
What's more, every JavaScript engine (back as far as the first implementation in Netscape 2) supports `Math.random`, so it's a quite pointless check.
bobince
A: 

It's a test to see if the Math variable is non-null/undefined. I've never seen it before, but I assume it's to prevent an error if, for some reason, Math is null (although, I can't imagine why that would happen).

David Wolever
Is it really that hard to imagine some idiot deciding to use Math as a variable? Ah, the joy of dynamic languages.
mikerobi
A: 

There, your Javascript code is :

  • Testing if the Math object exists
    • and has a random method
  • If yes, using it to generate a random value
  • else, using the date as fallback to get a random value


In you PHP code, you know that rand() and mt_rand() exist ; no need to test if they do ;-)

Which means the tests and condition are useless, and that you don't need to re-code them in PHP : just keep the part between the ? and the : in the original code.

Pascal MARTIN
+1  A: 

It may just be the ternary operator that is throwing you off.

http://en.wikipedia.org/wiki/Ternary_operation

Nick