Jump to content

problem with array_rand


Go to solution Solved by requinix,

Recommended Posts

I'm not sure why but i'm having problem with array rand. I made the following script to test out a real time price update over websockets, to see how it looks visually when the prices are updating and debug/fine tune the client side of the price updates.  so i decided i'd use array rand to select a value at random and insert it into the two test markets last_price field. the problem is, for some reason it is inserting the numeric key instead of the value. this is the first time i've used array rand, and i was wondering if someone could explain to me what i did wrong here. thanks

require_once __DIR__ . '/models/config.php';

for($i = 0; $i < 20; $i++) {
	$prices = array('0.00321252','0.00223252','0.00121252','0.00301272','0.00091252','0.00001252','0.00005252','0.00007252');
	$price1 = array_rand($prices);
	$price2 = array_rand($prices);
	$coin1  = 'TST-BTC';
	$coin2  = 'TST-LTC';
	global $mysqli;
	$stmt = $mysqli->prepare("UPDATE uc_market_data SET last_price = ? WHERE pair = ?");
	$stmt->bind_param('ss',$price1,$coin1);
	$stmt->execute();
	$stmt->close();
	$stmt = $mysqli->prepare("UPDATE uc_market_data SET last_price = ? WHERE pair = ?");
	$stmt->bind_param('ss',$price2,$coin2);
	$stmt->execute();
	$stmt->close();
	sleep(1);
}
Link to comment
https://forums.phpfreaks.com/topic/288026-problem-with-array_rand/
Share on other sites

  • Solution

When in doubt, check the documentation.

mixed array_rand ( array $array [, int $num = 1 ] )

 

Picks one or more random entries out of an array, and returns the key (or keys) of the random entries.

So

$price1 = $prices[array_rand($prices)];
$price2 = $prices[array_rand($prices)];
This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.