Chempooro
Chempooro

Reputation: 435

Add values Created from function into an array : PHP

Now What I have is a Function that generates random no between 0 to 1,

The no's are being displayed but not in neat and clean manner.

They displayed in the following Manner

0.53877228150880.596439828589210.552455397945230.777443517235050.0105479111044660.599950280560520.991422391976530.167267204630470.259013057761240.52319398085771

So What I want to do is that to store the values into an array, so that I can process them further.

Here is my Code:

<?php
header("Content-type: text/json");

function random_float($min,$max) 
{
  // $r_array =  ;
   $r_array  = ($min+lcg_value()*(abs($max-$min)));
   echo json_encode($r_array) ;
}


for ($i=0; $i<10; $i++)
{

  random_float(0,1) ;
}

?>

I am not able to add the values into single array, although I am able to get single single array of values.

Expected Output:

The Expected output should be something like :

[0.5387722815088, 0.59643982858921, 0.55245539794523, 0.77744351723505, 0.010547911104466,  0.59995028056052, 0.99142239197653, 0.16726720463047, 0.25901305776124, 0.52319398085771]

Upvotes: 4

Views: 69

Answers (2)

rahul bhangale
rahul bhangale

Reputation: 86

Here is your corrected code to get the expected output.

<?php
header("Content-type: text/json");
    function random_float($min,$max) {
        return ($min+lcg_value()*(abs($max-$min)));
    }
    for ($i=0; $i<10; $i++) {
        $r_array[] = random_float(0,1) ;
    }
    echo json_encode( $r_array )
?>

Upvotes: 1

Vaibhavi S.
Vaibhavi S.

Reputation: 1093

This should Works

header("Content-type: text/json");

function random_float($min,$max) 
{
  // $r_array =  ;
   $r_array  = ($min+lcg_value()*(abs($max-$min)));
   return $r_array;
//    echo json_encode($r_array) ;
}

$array = [];
for ($i=0; $i<10; $i++)
{

  $array[] = random_float(0,1) ;
}
echo json_encode($array) ;

OUTPUT

[0.9998815681439768,0.3570341541889031,0.4645344811447275,0.6411550648177741,0.5071643975962473,0.7722400176344946,0.814821318580633,0.6588660718711201,0.1678138905310088,0.6427063115962541]

Upvotes: 2

Related Questions