I don't know what to do with the probability draw - php

I am currently giving a score of one or more people and choosing to draw more than one person based on the score. However, there is still a runtime error and is not being resolved. Please let me know how to this problem solve.
this is my code:
$selectChildrens = array();
for($i=0;$i<$recuTotal;$i++){
$random = rand(0,sizeof($childSelectArray)-1);
$selectChild = $childSelectArray[$random];
$sameCheck = 0;
if(sizeof($selectChildrens) == 0){
array_push($selectChildrens,$selectChild);
while(($key = array_search($selectChild,$childSelectArray)) != NULL){
unset($childSelectArray[$key]);
}
$recuTotal—;
$i=0;
}else{
array_push($selectChildrens,$selectChild);
while(($key2 = array_search($selectChild,$childSelectArray)) != NULL){
unset($childSelectArray[$key2]);
}
$recuTotal—;
$i=0;
}
}

I see that your attempt to decrement $recuTotal is not using correct syntax.
Use this line instead: $recuTotal--
You are using a long dash, but need two hyphens.
As for your array_search() lines, I always use: !==false though I'm not sure it matters.
Lastly, you can use !sizeof($selectChildrens) as a shorter if statement.
Though I'll admit I didn't fully comb your code to see what it is doing, this is a DRYer code block that will perform the same way:
$selectChildrens = array();
for($i=0;$i<$recuTotal;$i++){
$random = rand(0,sizeof($childSelectArray)-1);
$selectChild = $childSelectArray[$random];
$sameCheck = 0;
array_push($selectChildrens,$selectChild);
while(($key=array_search($selectChild,$childSelectArray))!==false){
unset($childSelectArray[$key]);
}
$recuTotal--;
$i=0;
}

Related

Performance, check if value exists array or query

I need to check if a value exists in my database
I have a table where every user has an unique code. For example: 5h27f.
These values and users add up very quickly. So very soon I might have +2000 unique codes. What's the best, fastest and most efficient way to check if a value is unique?
foreach ($users as $user) {
$is_unique = FALSE;
while ($is_unique == FALSE) {
$code = unique_code();
$query = "SELECT * FROM unique_code_table WHERE code='$code';";
$res = $mysqli->query($query);
if ($res->num_rows > 0 {
} else {
$is_unique = TRUE;
}
}
}
OR
$query = "SELECT code FROM unique_code_table;";
$res = mysqli->query($query);
$codes = array();
$i = 0;
while ($row = $res->fetch_object()) {
$codes[$i] = $row->code;
$i++;
}
$code = unique_code();
while (in_array($code, $codes) {
$code = unique_code();
}
(this code might not be 100% accurate, I've written this just to explain the purpose of the question.)
I'd say that one query trip to the database vs. potentially 2000+ is significantly better to do. Second script will be significantly faster.
On the first code a LIMIT 1 would do wonders but compared to the second query it will pale as far as benchmarks are concerned.
Put the following at the bottom of your script to fine tune and benchmark:
PHP 5.4 +
$sParseTime = microtime(true) - $_SERVER["REQUEST_TIME_FLOAT"];
echo $sParseTime;

Pulling specific random values from php array

On the page I'm creating there is graphic representation of pigeon-holes with five compartments for new comments. If there is new unread comment it should show up as graphic in one random compartment. But it won't happen if all of the 5 are
already occupied. So if someone writes new comment I like the code to check for if there is already five of them taken, and if not, than to randomly occupied one of the remaining ones. So "new_c" stands for number of
unread (new) comments, and c1-c5 stands for compartments. Value 0 means empty compartment for each "c". I was trying to make code that would first separate new_c from rest of the array after knowing the number is smaller than 5,
so I'm only working with 5 compartments. And than to determine which one is/are empty. And then randomly choose one empty to occupy. It's not really working as it is I probably am not using that array_keys properly as c2 is changed to some other value than 0 but still is being echoed, there is probably also a better/more efficient way to achieve that. I will really appreciate some input.
<?php
$tucQuery = "SELECT new_c,c1,c2,c3,c4,c5 FROM users WHERE id = '{$author_id}' LIMIT 1";
$result_tuc = mysqli_query($connection, $tucQuery);
$tucArray = mysqli_fetch_assoc($result_tuc);
mysqli_free_result($result_tuc);
$new_c = $tucArray[0];
if($new_c < 5){
$new_array = array_keys((array_slice($tucArray,1)), 0);
$rand_zero = array_rand($new_array, 1);
echo $rand_zero + 1;
}
?>
Bellow code works but it doesn't seem to be efficient and there is probably a better way.
if($new_c < 5){
$empties = array();
if($tucArray['c1'] == 0){
$empties[] = 1;
}
if($tucArray['c2'] == 0){
$empties[] = 2;
}
if($tucArray['c3'] == 0){
$empties[] = 3;
}
if($tucArray['c4'] == 0){
$empties[] = 4;
}
if($tucArray['c5'] == 0){
$empties[] = 5;
}
print_r($empties);
$rand_zero = array_rand((array_flip($empties)), 1);
echo $rand_zero;
}

PHP crawling data from website

I am currently trying to crawl alot of data from a website, however I am struggling a little bit with it. It has an a-z index and 1-20 index, so it has a bunch of loops and DOM stuff in there. However, it managed to crawl and save about 10.000 rows at first run, but now I am at around 15.000 and it is only crawling around 100 per run.
It is probably because it has to skip the rows that it already has inserted, (made a check for that). I cant think of a way to easily skip some pages, as the 1-20 index varies a lot (for one letter there are 18 pages, other letter are only 2 pages).
I was checking if there already was an record with the given ID, if not, insert it. I assumed that would be slow, so now before the script stars I retrieve all rows, and then check with an in_array(), assuming thats faster. But it just wont work.
So my crawler is navigating 26 letters, 20 pages each letter, and then up to 50 times each page, so if you calculate it, its a lot.
Thought of running it letter by letter, but that wont really work as I am still stuck at "a" and cant just hop onto "b" as I will miss records from "a".
Hope I have explained the problem good enough for someone to help me. My code kinda looks like this: (I have removed some stuff here and there, guess all the important stuff is in here to give you an idea)
function in_array_r($needle, $haystack, $strict = false) {
foreach ($haystack as $item) {
if (($strict ? $item === $needle : $item == $needle) || (is_array($item) && in_array_r($needle, $item, $strict))) {
return true;
}
}
return false;
}
/* CONNECT TO DB */
mysql_connect()......
$qry = mysql_query("SELECT uid FROM tableName");
$all = array();
while ($row = mysql_fetch_array($qru)) {
$all[] = $row;
} // Retrieving all the current database rows to compare later
foreach (range("a", "z") as $key) {
for ($i = 1; $i < 20; $i++) {
$dom = new DomDocument();
$dom->loadHTMLFile("http://www.crawleddomain.com/".$i."/".$key.".htm");
$finder = new DomXPath($dom);
$classname="table-striped";
$nodes = $finder->query("//*[contains(concat(' ', normalize-space(#class), ' '), ' $classname ')]");
foreach ($nodes as $node) {
$rows = $finder->query("//a[contains(#href, '/value')]", $node);
foreach ($rows as $row) {
$url = $row->getAttribute("href");
$dom2 = new DomDocument();
$dom2->loadHTMLFile("http://www.crawleddomain.com".$url);
$finder2 = new DomXPath($dom2);
$classname2="table-striped";
$nodes2 = $finder2->query("//*[contains(concat(' ', normalize-space(#class), ' '), ' $classname2 ')]");
foreach ($nodes2 as $node2) {
$rows2 = $finder2->query("//a[contains(#href, '/loremipsum')]", $node2);
foreach ($rows2 as $row2) {
$dom3 = new DomDocument();
//
// not so important variable declarations..
//
$dom3->loadHTMLFile("http://www.crawleddomain.com".$url);
$finder3 = new DomXPath($dom3);
//2 $finder3->query() right here
$query231 = mysql_query("SELECT id FROM tableName WHERE uid='$uid'");
$result = mysql_fetch_assoc($query231);
//Doing this to get category ID from another table, to insert with this row..
$id = $result['id'];
if (!in_array_r($uid, $all)) { // if not exist
mysql_query("INSERT INTO')"); // insert the whole bunch
}
}
}
}
}
}
}
$uid is not defined, also, this query makes no sense:
mysql_query("INSERT INTO')");
You should turn on error reporting:
ini_set('display_errors',1);
error_reporting(E_ALL);
After your queries you should do an or die(mysql_error());
Also, I might as well say it, if I don't someone else will. Don't use mysql_* functions. They're deprecated and will be removed from future versions of PHP. Try PDO.

Using while() and continue in PHP

I am learning PHP and trying to use the while and continue expressions correctly.
I have a script that creates a 6 digit PIN, and I want to ensure that it is unique, otherwise I want to generate another PIN.
while(1) {
$pin = rand(111111,999999);
$sel = mysql_query("SELECT * FROM formusers WHERE pin = '$pin'");
if(mysql_num_rows($sel) != 0) { continue; }
mysql_query("INSERT INTO formusers(email,password,pin) VALUES('".$_POST['srEmail']."','".$_POST['srPass']."','".$pin."')");
if(mysql_affected_rows()!=-1) {
echo "Pin:" . $pin;
exit;
} else {
echo "Existing email, try again<br />";
}
break;
}
Do I have the syntax for the loop correct? It seems to work, but there's no way for me to debug it in the instance the rand() function creates the same PIN twice.
Also, in the event I did run out of unique PINs, what would happen here? Presumably it would loop indefinitely? Is there any way to prevent this?
Yeah, the code works, but as stated the infinite loop is concerning. You could possibly solve that like this:
var $i = 0;
while($i < 10) {
$i++;
$pin = rand(111111,999999);
$sel = mysql_query("SELECT * FROM formusers WHERE pin = '$pin'");
if(mysql_num_rows($sel) != 0) { continue; }
mysql_query("INSERT INTO formusers(email,password,pin) VALUES('".$_POST['srEmail']."','".$_POST['srPass']."','".$pin."')");
if(mysql_affected_rows()!=-1) {
echo "Pin:" . $pin;
exit;
} else {
echo "Existing email, try again<br />";
}
break;
}
This would ensure you would never make more than 10 iterations. However, the larger problem is probably that even that sampling size won't work in the future. This presents a bit of a conundrum. One possible approach is to determine how many unique numbers exist before starting the loop by counting them and then iterate that many times, but that approach is something like n2 (maybe, I'm not real good on big-O, I just know it would be bad).
You can leverage the unique nature of php array keys for this.
function getPins($qty){
$pins = array();
while (count($pins) < $qty){
$pins[rand(111111,999999)] = "";
}
return array_keys($pins);
}
This will make sure that for a given run you will get $qty number of unique pins. You might want to look at appending a unique prefix to each run of the function to avoid multiple runs creating collisions between the two.
You can seed random, so it gives you the same values every time, you run it:
srand (55 ); //Or some other value.
The while loop syntax looks okay to me.

php array trouble

I'm a rookie with php arrays, and have a problem. I downloaded a blackjack PHP script, it stores the current players hand, deck, and dealers hand in THE $_POST, which isn't good.
So I'm trying to alter it to store them in a database instead. I'm getting errors and this is the code I'm playing with. The original code for drawing a random card from the deck is this:
shuffle($deck);
for ($i = 0; $i < 2; $i++) {
$hand[] = array_shift($deck);
$dealer[] = array_shift($deck);
}
$handstr = serialize($hand);
$deckstr= serialize($deck);
$dealerstr= serialize($dealer);
This works, but what I want to do is only draw a random card if theres no data in the database already. If the user draws, someone could just refresh the page to get a different hand. I want to do something like this:
if ($rs5[hand] == "") {
shuffle($deck);
for ($i = 0; $i < 2; $i++) {
$hand[] = array_shift($deck);
$dealer[] = array_shift($deck);
}
$handstr = serialize($hand);
$deckstr= serialize($deck);
$dealerstr= serialize($dealer);
} else {
$dealer = $rs5[dealer];
$hand = $rs5[hand];
$deck = $rs5[deck];
}
Im getting errors with this, I don't know what I'm doing with arrays really, can anyone point me in the right direction?
I'm not terribly sure what you're trying to do, but for starters:
$dealer = $rs5[dealer];
$hand = $rs5[hand];
$deck = $rs5[deck];
Should probably be:
$dealer = $rs5[$dealer];
$hand = $rs5[$hand];
$deck = $rs5[$deck];
Note the dollar signs on the index variables.
You could do:
if (empty($hand))
or:
if (count($hand) == 0)

Categories