KNOWLEDGE BASE
Log In    |    Knowledge Base    |    4D Home
Tech Tip: Using PHP's rand() function to generate random numbers in 4D v12
PRODUCT: 4D | VERSION: 12 | PLATFORM: Mac & Win
Published On: May 14, 2010

Here is a quick wrapper for using the PHP rand() function within 4D v12:

// ----------------------------------------------------
// Method: phpRandom
//
// Description: Returns a Random number using PHP's rand() function
//
// Required Parameters: none
//
// Optional Parameters: 2 (must specify both or none)
// $1 = Min value for Random number
// $2 = Max value for Random number
//
// ----------------------------------------------------


C_LONGINT($0;$randResult) // random number result

If (Count parameters=2)
  C_BOOLEAN($phpSuccess)
  C_LONGINT($1;$randMin) // Random min value
  C_LONGINT($2;$randMax) // Random max value
  $randMin:=$1
  $randMax:=$2
  $phpSuccess:=PHP Execute("";"rand";$randResult;$randMin;$randMax)
  $0:=$randResult
Else
  If (Count parameters=0)
    C_BOOLEAN($phpSuccess)
    $phpSuccess:=PHP Execute("";"rand";$randResult)
    $0:=$randResult
  Else
    $0:=-1
  End if
End if


The above example uses the rand() function from PHP, which by default (as of this writing) uses the libc random number generator.

PHP also offers an alternative random generator, the mt_rand() function; this uses the Mersenne Twister. The following example uses mt_rand():

// ----------------------------------------------------
// Method: phpRandom_mt
//
// Description: Returns a Random number using PHP's mt_rand() function
//
// Required Parameters: none
//
// Optional Parameters: 2 (must specify both or none)
// $1 = Min value for Random number
// $2 = Max value for Random number
//
// ----------------------------------------------------


C_LONGINT($0;$randResult) // random number result

If (Count parameters=2)
  C_BOOLEAN($phpSuccess)
  C_LONGINT($1;$randMin) // Random min value
  C_LONGINT($2;$randMax) // Random max value
  $randMin:=$1
  $randMax:=$2
  $phpSuccess:=PHP Execute("";"mt_rand";$randResult;$randMin;$randMax)
  $0:=$randResult
Else
  If (Count parameters=0)
    C_BOOLEAN($phpSuccess)
    $phpSuccess:=PHP Execute("";"mt_rand";$randResult)
    $0:=$randResult
  Else
    $0:=-1
  End if
End if