PHP rand function giving empty values - still not working - php

I have this little tid-bit of my code, which is eventually sent to a MySQL database. The rest of the code is sound, but this code likes to give me empty data some of the time. Is there any way to prevent this from happening?
Edit: Here's the whole chunk
//random Species
$sp_one = mt_rand(1,10);
$one_species = "Water Leaper";
//random Genetics
if($one_species == "Water Leaper")
{
$one_gene = mt_rand(1,5);
if($one_gene < 3)
{
$one_genetics = "1";
}
else if($one_gene < 5)
{
$one_genetics = "2";
}
else
{
$one_genetics = "3";
}
}
//random Gender
$one_sex_num = mt_rand(1,2);
if($one_sex_num == 1)
{
$one_gender = "Female";
}
if($one_sex_num == 2)
{
$one_gender = "Male";
}
//Entering it
$sql="INSERT INTO creatures (species, sex, location, genetics)
VALUES('{$one_species}','{$one_gender}', 's1','{$one_genetics}')";
mysqli_query($con,$sql);

First, your if clauses seem a bit redundant. More concise code:
if ($one_gene <3) { $one_genetics = "1"; }
elseif ($one_gene <5) { $one_genetics = "2"; }
else { $one_genetics = "3"; }
This should always return a value - if everything else fails, "3".
Maybe better even:
$one_genetics = ($one_gene + 1) / 2; // integer division

I don't know what you are doing exacly but maby you can take a look at this:
<?php
$animals = array();
$animals[] = array('dog', 78, array('Komondor','Old English Sheepdog'));
$animals[] = array('Drosophila', 8, array('Vestigal','Ebony'));
$number_animals = count($animals) - 1;
$list_size = 30;
for($q = 1; $q <= $list_size; $q++){
$rand = rand(0, $number_animals);
$animal = $animals[$rand];
$number_species = count($animal[2]) - 1;
$rand = rand(0, $number_species);
$randsex = rand(0, 1);
$species = $animal[2][$rand];
$sex = ($randsex ? 'male' : 'female');
$genes = $animal[1];
echo "$q: $species - $sex - $genes <br>";
}
?>
See a live demo at: here
It pics random animals with specs if you want you can modify to your own wishes.

Related

How to do addition between two dropdown menus containing 1-5?

This is the code I have so far. I'm trying to use two dropdown menus in my HTML form that contains a 1-5 each and simply add them using POST.
//action for dropdown menu addition
$dropdownValueA = $_POST["dropdown1"];
$dropdownValueB = $_POST["dropdown2"];
$valueone = 0;
$valuetwo = 0;
if ($dropdownValueA == "1a"){
$valueone = 1;
}
if ($dropdownValueA == "2a"){
$valueone = 2;
}
if ($dropdownValueA == "3a"){
$valueone = 3;
}
if ($dropdownValueA == "4a"){
$valueone = 4;
}
if ($dropdownValueA == "5a"){
$valueone = 5;
}
if ($dropdownValueB == "1b"){
$valuetwo = 1;
}
if ($dropdownValueB == "2b"){
$valuetwo = 2;
}
if ($dropdownValueB == "3b"){
$valuetwo = 3;
}
if ($dropdownValueB == "4b"){
$valuetwo = 4;
}
if ($dropdownValueB == "5b"){
$valuetwo = 5;
}
echo $valueone + $valuetwo;
It's totally not clear what is your problem and what is not works as expected. But your code is... not good :) Maybe try something like
if( preg_match('/^([1-5])a$/', $dropdownValueA, $m) ) {
$valueone = $m[1];
}
if( preg_match('/^([1-5])b$/', $dropdownValueA, $m) ) {
$valuetwo = $m[1];
}
echo (int)$valueone + (int)$valuetwo;
If the numbers will always come first, this will be your best option.
$dropdownValueA = $_POST["dropdown1"];
$dropdownValueB = $_POST["dropdown2"];
$valueone = intval($dropdownValueA);
$valuetwo = intval($dropdownValueB);
echo $valueone + $valuetwo;
3v4l HERE

Detecting a cycle in an array PHP

I'm running a simple script which puts an integer through the formula of the Collatz conjecture and adds the output of each step into an array.
I want to use a function to detect if there's a cycle in the array, using Floyd's algorithm. And though I feel like I'm not doing a bad job, I don't seem to get it right. At this moment I'm getting the error Trying to get property 'next' of non-object in C:\xampp\htdocs\educom\week3\functions.php on line 12
See my code below. Any feedback is greatly appreciated!
include("functions.php");
$n = $_POST['number'];
$step = 0;
$reeks1 = array();
$cycle = 0;
echo "Your entry is: ". $n ."<br><br>";
while($n!==1 && $cycle==0){
$cycle = detect_cycle(array($reeks1));
if($n % 2 == 0){
$n = $n / 2;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}else{
$n = ($n * 3) + 1;
array_push($reeks1, "$n");
$step++;
echo $step .": ". $n ."<br>";
}
}
functions.php:
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node->next;
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit->next == NULL){
return FALSE;
}else{
$turtle = $turtle->next;
$rabbit = $rabbit->next->next;
}
}
return FALSE;
}
Check this out. IMPORTANT I don't know is this according to your theory. but it won't give you errors if you use like this.
function detect_cycle($node){
if ($node==NULL){
return FALSE;
}
$turtle = $node;
$rabbit = $node[0];
while($rabbit != NULL){
if($rabbit === $turtle){
return TRUE;
}elseif($rabbit[0] == NULL){
return FALSE;
}else{
$turtle = $turtle[0]; // use the number of the element key starting from 0
$rabbit = $rabbit[0][1];
}
}
return FALSE;
}

Choose a string based on random number

I am working on a bit of PHP and I've come upon a bit of issues.
I am using PHP to randomly choose a number from 1-360. I am trying to compare the answer to a list of value determined by range.
$NumberA = rand(0,180);
$NumberB = rand(0,180);
$NumberC = $NumberA + $NumberB;
if ($NumberC = range(0,21) {
$result = "Orange";
}
elseif ($NumberC = range(22,42) {
$result = "Red";
}
elseif ($NumberC = range(43,63) {
$result = "Blue";
}
//This goes on for a while ...
else {
$result = "Green";
}
echo = $result;
Anytime i do this, the result always assigns the value of "Orange" to $result .
Im sure im doing something wrong here, please help!
First of all, you used just one '=' to compare while it should have been '=='. Second range() generates an array and you cannot compare an integer to an array. Third why generating the range every single time when you can check that $NumberC lies between the minimum and the maximum numbers of the range?
Change your code to:
$NumberA = rand(0,180);
$NumberB = rand(0,180);
$NumberC = $NumberA + $NumberB;
if ($NumberC >= 0 && $NumberC <= 21) {
$result = "Orange";
} elseif ($NumberC >= 22 && $NumberC <= 42) {
$result = "Red";
} elseif ($NumberC >= 43 && $NumberC <= 63) {
$result = "Blue";
} else {
$result = "Green";
}
echo $result;
Shall work. Hope this helps.

Add unique identifier to first iteration in PHP for loop

I am using a for loop on my client's website to insert purchased ticket information into a database. The loop is working correctly, but the client has requested the option to attach a unique identifier to the first entry every time the for loop is run. This identifier would be used to highlight the primary ticket owner when the tickets are printed. I have included the current for loop below for reference. Any ideas on how to achieve this? Thank you.
$threepack = '';
$i = '';
for($i = 0; $i < $tickets; $i++)
{
$firstname = 'firstname'.$threepack;
$lastname = 'lastname'.$threepack;
$address = 'address'.$threepack;
$city = 'city'.$threepack;
$postal = 'postal'.$threepack;
$phone = 'phone'.$threepack;
$altphone = 'altphone'.$threepack;
$sec_firstname = 'sec_firstname'.$threepack;
$sec_lastname = 'sec_lastname'.$threepack;
$email = 'email'.$threepack;
$table->firstname = $data->$firstname;
$table->lastname = $data->$lastname;
$table->address = $data->$address;
$table->city = $data->$city;
$table->postal = $data->$postal;
$table->phone = $data->$phone;
$table->altphone = $data->$altphone;
$table->sec_firstname = $data->$sec_firstname;
$table->sec_lastname = $data->$sec_lastname;
$table->email = $data->$email;
$table->id = 0;
$table->order_total = $data->total;
$table->store();
if($data->tickets == '-1')
{
if($threepack == 2)
{
$threepack = 3;
} else {
$threepack = 2;
}
}
// 8 Fields
if($data->tickets == '5')
{
if ($threepack == '') {
$threepack = 2;
} else {
$threepack += 1;
}
}
}
for ($i = 0; $i < $tickets; $i++) {
// ...
if ($i == 0)
$table->highlightme = 1;
// ...
$table->store();
// ...
}

Optimized Logic to find high score

Basically this is related to a squash application where we have 2 scores. One is from winner point of view and another from loser point of view.
eg.
Score1: 11-5,11-5,11-5 (Winner point of view)
Score2: 5-11, 5-11,5-11 (Loser point of view)
Now in my logic i want to find which is the winner score and which is the loser score.
I have written my logic in the below way and it does work. But i want to know if their is any other better/optimized way of writing this.
$high1 = 0;
$high2 = 0;
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
$score1Array = explode(",",$score1);
$size = sizeof($score1Array);
for($i = 0; $i < $size; $i++) {
$checkscore1 = explode("-",$score1Array[$i]);
if($checkscore1[0] < $checkscore1[1]) {
$high1++;
}else if($checkscore1[0] > $checkscore1[1]) {
$high2++;
}
}
if($high1 > $high2) {
$winningScore = $score2;
$losingScore = $score1;
}else{
$winningScore = $score1;
$losingScore = $score2;
}
echo $winningscore;
echo $losingscore;
What about something like this:
function is_winning($score) {
$split_scores = preg_split('/(-|,)/', $score);
$wins = $losses = 0;
for($i = 0; $i < count($split_scores) / 2; $i += 2) {
if($split_scores[$i] > $split_scores[$i + 1])
$wins++;
if($split_scores[$i] < $split_scores[$i + 1])
$losses++;
}
return $wins > $losses;
}
Assuming $score is formatted as in your question. You can then use it like this:
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
if(is_winning($score1)) {
$winning_score = $score1;
$losing_score = $score2;
} else {
$winning_score = $score2;
$losing_score = $score1;
}
echo $winning_score;
echo $losing_score;
The idea is to split the score into an array where the even numbered indexes have the left score and the odd numbered indexes the right score. We then count the number of wins and the number of losses. If there's more wins then losses then we return true since the score was a winning score. If there's not more wins then losses we simply return false.
This should work
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
$l = $r = 0;
$score1_sets_arr = explode(',', $score1);
foreach ($score1_sets_arr as $set_score) {
$set_score_arr = explode('-', $set_score);
if ($set_score_arr[0] > $set_score_arr[1]) {
$l++;
} else {
$r++;
}
}
if ($l > $r) {
$winning_score = $score1;
$losing_score = $score2;
} else {
$winning_score = $score2;
$losing_score = $score1;
}
you can use this :
<?php
$high1 = 0;
$high2 = 0;
$score1 = "2-11,5-11,4-11,4-4";
$score2 = "11-2,11-5,11-4,4-4";
$explode = explode(",",$score1);
for($i=0;$i< sizeof($explode);$i++){
$explode2= explode("-", $explode[$i]);
if($explode2[0] <= $explode2[1]){
echo $explode2[0]."-";
echo $explode2[1]." ";
}
}
echo "<br />";
for($i=0;$i< sizeof($explode);$i++){
$explode2= explode("-", $explode[$i]);
if($explode2[1] >= $explode2[0]){
echo $explode2[1]."-";
echo $explode2[0]." ";
}
}
?>
for Winner point of view, all big score in left,otherwise in right. so u can just detect the first score.
$score1Array = explode(",",$score1);
$checkscore1 = explode("-",$score1Array[$i]);
if($checkscore1[0] < $checkscore1[1]) {
echo $score2;
echo $score1;
}else{
echo $score1;
echo $score2;
}
Fix: above code is wrong,try this:
$score1value = eval(str_replace(",","+",$score1));
$score2value = eval(str_replace(",","+",$score2));
if($score1value < $score2value) {
echo $score2;
echo $score1;
}else{
echo $score1;
echo $score2;
}

Categories