Hello everyone, I need to be able to grab a random variable from a list. This is how my script chooses which IP to use from my server for outgoing connections. In the past i had a range of IP addresses that were only 1 number off from each other. For example i had 2.2.2.10 - 2.2.2.20, so i used the following code. $first_number = 2; $second_number = 2; $third_number = 2; $fourth_number = rand(10,20); $ip = $first_number.'.'.$second_number.'.'.$third_number .'.'.$fourth_number; $toSet[CURLOPT_INTERFACE] = $ip; PHP: This would cycle through all of my IP's. Now i have a new range on my server (for example 3.3.3.40 - 3.3.3.50) in addition to my original range, i can't change my variables above to work properly to only come up with an outcome that is an IP on my server. So i think the best thing would be to choose from a random array of a list of all the IP's i have ? Though im not sure how exactly to do this properly, i did some testing and i can't seem to get it right.
if the 4th number (i.e. unsigned 8bits only) need to be feed random, then your existing method is fine. Or create a large array of all possible ip's or put them in database. //Choosing random among array elements $IPS = Array('2.2.2.10','2.2.2.10','2.2.2.10','2.2.2.10',........................ AND SO ON ); srand(time()); //seed start of PRNG $ip = $IPS[ rand(0, count($IPS)-1) ]; PHP: #Choosing random from list of IP's in database table SELECT * FROM `my_ip_table` ORDER BY RAND() LIMIT 1 Code (markup): Besides you can use ip2long and long2ip functions for better performance, when you have multi-threaded application to create a lot connections simultaneously. I hope it helps.
$input = array("Neo", "Morpheus", "Trinity", "Cypher", "Tank"); $rand_keys = array_rand($input, 1); echo $input[$rand_keys[0]];
little correction here, array_rand returns index of the element when selecting 1 element not an array. Code above will produce undefined index kind of warning, so use: $rand_index = array_rand($input, 1); echo $input[$rand_index]; PHP: Probably shuffle will do the same job too as below (but recommended is single call and that is faster because if PRNG is called by interpreter will be faster than the one called in interpreted script) shuffle($IPS); //will shuffle indexex, becareful $ip = $IPS[ 0 ]; //and pick the first element PHP: regards
Hey everyone, Thanks for all the suggestions, all worked but i found that Vooler's was the best for what i needed. Thanks again Twam