On a website I have a number of small PHP scripts to automate changes to the text of the site, depending on a figure that's calculated from a MySQL database. The site is for a fundraising group, and the text in question on the home page gives the total amount raised.
The amount raised is pulled from the database and rounded to the nearest thousand. This is the PHP I use to round the figure and find the last three digits of the total:
$query4 = mysql_query("SELECT SUM(amountraised) AS full_total FROM fundraisingtotal;");
$result4 = mysql_fetch_array($query4);
$fulltotal = $result4["full_total"];
$num = $fulltotal + 30000;
$ftotalr = round($num,-3);
$roundnum = round($num);
$string = $roundnum;
$length = strlen($string);
$characters = 3;
$start = $length - $characters;
$string = substr($string , $start ,$characters);
$figure = $string;
(£30,000 is the amount that had been raised by the previous fundraising team from when the project first started, which is why I've added 30000 to $fulltotal for the $num variable)
Currently the text reads:
the bookstall and other fundraising events have raised more than £<? echo number_format($ftotalr); ?>
I've just realised though that because the PHP is rounding to the nearest thousand, if the total's for example £39,200 and it's rounded to £40,000, to say it's more than £40,000 is incorrect, and in that case I'd need it to say 'almost £40,000' or something similar. I obviously need to replace the 'more than' with a variable.
Obviously I need to test whether the last three digits of the total are nearer to 0 or 1000, so that if the total was for example £39,2000, the text would read 'just over', if it was between £39,250 and £39,400 something like 'over', between £39,400 and £39,700 something like 'well over', and between £39,700 and £39,999, 'almost.'
I've managed to get the last three digits of the total as a variable, and I think I need some sort of an if/else/elseif code block (not sure if that would be the right approach, or whether to use case/break), and obviously I'm going to have to check whether the figure meets each of the criteria, but I can't figure out how to do that. Could anyone suggest what would be the best way to do this please?
Instead of nested if else blocks, you could have a function that takes in the dollar amount and inside the function throw the variable in a switch case statement and at a particular case return the correct echo'd text.
Switch cases provide readability over several if else statements. If you need coIde examples, let me know.
Update:
Performing comparisons on integers only, switch case is the best bet. When comparing conditions that result in a boolean value, using if else is what you need.
I had took your code and switched the case to be if else and here is what it looks like with an example output:
function qualifier($figure) {
if ($figure < 249) return "just over";
elseif ($figure < 399) return "over";
elseif ($figure < 699) return "well over";
elseif ($figure < 999) return "almost";
else return "No number entered";
}
echo "We are " . qualifier(250) . " our goal!";
// outputs: "We are over our goal!"
The simplest and most elegant solution imho would be, like Lizard pointed out, to floor the value and always say "over". You could even make exception for the first-1000 problem and floor anything below that to the next 100 or so, something like...
<?
function getFlooredText($amount) {
if($amount < 1000) {
return floor($amount/100)*100;
} else {
return floor($amount/1000)*1000;
}
}
echo "We've raised over £" . getFlooredText(455) . "\n"; // 400
echo "We've raised over £" . getFlooredText(1455) . "\n"; // 1000
echo "We've raised over £" . getFlooredText(38800) . "\n"; // 38000
?>
If you absolutely don't want that you could always do a four or five layer if-sandwich, it would be the easiest approach towards the idea you described but maybe not the prettiest. Something like this, if I understood where you were going with it...
<?
function getRoundedText($amount) {
$n = substr($amount, -3);
if($n < 250) {
return "just over £" . round($amount, -3);
} elseif($n < 500) {
return "well over £" . round($amount, -3);
} elseif($n < 750) {
return "close to £" . round($amount, -3);
} elseif($n < 1000) {
return "almost £" . round($amount, -3);
}
}
echo "We've raised " . getRoundedText(38200) . "\n";
echo "We've raised " . getRoundedText(38400) . "\n";
echo "We've raised " . getRoundedText(38700) . "\n";
echo "We've raised " . getRoundedText(38900) . "\n";
?>
Hope that helps.
You might not need to change the text... take a look at the floor function http://php.net/manual/en/function.floor.php
It will always round down, so you can still say 'more than'.
I would use "approximately" to cover all cases!
Related
I have a database containing tweets. Furthermore, I have classified these tweets as either being 'negative', 'neutral' or 'positive'. I have done so manually and am now trying to figure out how well my computer could classify them, based on a Naive Bayes classifier.
For testing the accuracy of classification (the amount of tweets classified by the computer in the same way as I did manually divided by the total amount), a script has been written.
I however face a problem with this PHP script. When running it, it gives the error 'Division by zero in C:\wamp\and-so-on'. This is probably due to the fact that the counter is not updated. Furthermore, the amount of 'right classes' do not seem to be updated either. These two parts are essential as the formula for accuracy is: 'right classes' divided by 'counter'.
My question is: what do you think the problem is when looking at the script? And how could I potentially fix it?
The script for testing:
$test_array = array();
$counter = 0;
$timer1 = microtime(true);
$right_classes = 0;
foreach ($test_set as $test_item) {
$tweet_id = $test_item['tweet_id'];
$class_id_shouldbe = $test_item['class_id'];
$tweet = Tweets::loadOne($tweet_id);
// # Preprocess if not done already
// $steps->processTweet($tweet_id, $tweet);
// $tweet = Tweets::loadOne($tweet_id);
if ((int) $tweet['classified'] > 0 || !$tweet['valid']) continue;
if (strlen($tweet['processed_text']) == 0) {
$steps->processTweet($tweet_id, $tweet);
$tweet = Tweets::loadOne($tweet_id);
if (strlen($tweet['processed_text']) == 0) {
echo "Kon tweet '$tweet_id' niet processen. <br>";
continue;
}
}
$class_id = $classifier->classify($tweet['processed_text']);
# Add tweets in database
// Tweets::addClassId($tweet_id, $class_id_shouldbe);
$test_array[$tweet_id] = array(
'what_human_said' => $class_id_shouldbe,
'what_classifier_said' => $class_id,
);
if ($class_id_shouldbe == $class_id) $right_classes++;
$counter++;
if ($counter > 936) break;
echo "$tweet_id,$class_id_shouldbe,$class_id<br>";
}
$timer2 = microtime(true);
echo '<br><br>klaar in '.round($timer2-$timer1, 3).' sec<br>';
echo ($right_classes/$counter)*100 .' %';
exit();
first of all just fix error, and then try to verify why $counter is zero. To fix $counter just verify before division:
if($counter!=0) echo ($right_classes/$counter)*100 .' %'; else echo '0 %';
Then looking at your code, you use continue to get next item in foreach then it's not guaranteed that $counter is reached and then you get Division by zero error.
Hope it helps!
Im trying to get out an average value from a vote function.
<?php
$file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = str_split($textfil);
echo "Number of votes: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum = $sum + intval($vote);
}
echo "Average: " . $sum;
?>
Simple by substitute (+) with a (/), and even tried a (%). But still getting error message.
Would appreciate alot if anyone could help me out and tell me what im doing wrong.
/thanks
Edit
Sidenote: Please read an explanation under "First answer given" further down below.
This version will take into account any blank lines in a file, if the content looks like:
1
2
3
// <- blank line
Sidenote: Please provide a sample of your text file. A comment has already been given to that effect.
PHP
<?php
// first line not required
// $file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = array_filter(array_map("trim", file("textfile.txt")), "strlen");
echo "Number of votes: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum += intval($vote);
}
$avg = $sum / count($textfill);
echo "Average: " . $avg;
?>
First answer given
Using the following in a text file: (since no example of file content was given)
5
5
5
IMPORTANT NOTE: There should not be a carriage return after the last entry.
produced
Number of votes: 5
Average: 3
which is false, since there are 3 entries in the text file.
explode() should be used, and not str_split()
The following using the same text file produced:
Number of votes: 3
Average: 5
which is correct. In simple mathematics, averages are done by adding all numbers then dividing them by how many numbers there are.
In this case it's 3 numbers (all 5's) added equals 15, divided by 3 is 5.
Sidenote: The first line is not required $file = file("textfile2.txt");
<?php
// first line not required
// $file = file("textfile.txt");
$textfil = file_get_contents("textfile.txt");
$textfill = explode("\n", $textfil);
echo "Number of votes: " . count($textfill) . "<br>";
$sum = 0;
foreach ($textfill as $vote) {
$sum += intval($vote);
}
$avg = $sum / count($textfill);
echo "Average: " . $avg;
?>
Footnotes:
If the average comes out to 8.33333 and you would like it to be rounded off to 8, use:
echo "Average: " . floor($avg);
If the average comes out to 8.33333 and would like it to be as 9 you would use:
echo "Average: " . ceil($avg);
ceil() function
floor() function
You may be mixing in stuff that can't be divided, like text, etc. I don't know what your text file looks like. intval may be having a problem with arrays. You may try:
foreach ($textfill as $vote) {
if(is_int($vote) {
$sum += $vote;
}
}
echo "Average: " . $sum;
Lower school math says:
foreach ($textfill as $vote) {
$sum += intval($vote);
}
$avg = $sum / count($textfill);
The average value is calculated by divide the sum with the number of votes. This line will print the average value:
echo "Average: " . $sum/count($textfill);
I have written a little script to automate some calculations for me. It is pretty simple.
1*3=3
2*3=6
3*3=9 and so on. When the answer(product) is more than one digit long I want it to add the digits of the answer.
3*4=12 || 1+2=3.
I want it to automatically add the answer if it is more than one digit no matter how many times adding the answer arrives larger than a single digit.
as in when you reach 13*3=39 || 3+9=12 || 1+2=3
Currently my code does not loop, and i cannot figure out how to make it loop here.
http://screencast.com/t/MdpQ9XEz
Also, it is not adding up more than 2 digit answers see 34*3=102. any help here to allow it infinity addition would be great.
As each line is produced the answers get larger, so it should add as many digits there are in the answer.
here is my code:
$i = 1; //Start with one
function count_digit($number) {
return strlen((string) $number);
};
while($i < 500){
$product = $i * 3; //Multiply set
$number_of_digits = count_digit($product); //calls function to count digits of $sum
if($number_of_digits > 1){ //if $sum has more than one digit add the digits together
$addproduct = strval($product);//seperates the digits of $sum
$ii = 0;
while($ii <= $number_of_digits -1){
$io = $ii + 1;
if($io < $number_of_digits){
$one = intval($addproduct[$ii]);
$two = intval($addproduct[$io]);
$sum = $one + $two;
print($i . ' * 3 = ' .$product. ' || ' .$one. ' + ' .$two. ' = ' .$sum. '<br>');
};$ii++;
};
}else{
Print ($i . ' * 3 = ' .$product.'<br>'); //Print Set
};
$i++; //add one
}
For a start, you might replace the $i=1, while ..., and $i++ into one statement: for ($i=0; $i<500; $i++) {.... - see http://nz1.php.net/manual/en/control-structures.for.php for more information about for loops. It comes out to effectively the same code, but keeps the three parts (initialisation, test, increment counter) together; it makes it clear that they are related, and quicker to understand.
Next I would replace conversion of the number to a string, seeing if the length of the string is greater than one, etc.... with:
while ($product>10) {
$out=0;
while ($product) {
$out+=$product%10;
$product=(integer)($product/10);
}
$product=$out;
}
Note that at no time am I treating a number as a string - I avoid that wherever possible.
In case you are not familiar with it, $something+=$somethingelse is the same as $something=$sometime+$somethingelse, just a shorthand. $out is the running total, and each time around the inner loop (while $product), $out is increased by the rightmost digit (the ones column): $out+=$product%10 - see http://nz2.php.net/operators.arithmetic for more info, then $product is divided by 10 and converted to an integer, so 12 becomes 1.2, then 1, dropping the right-most digit.
Each time the inner loop is complete (all the digits of $product are used up, and $product is 0), the result (in $out) is copied to $product, and then you get back to the outer loop (to see if the sum of all these digits is now less than 10).
Also important is exactly where in each loop you print what. The first part, with the multiplication, is immediately in the '500' loop; the '||' happens once for each time '$product' is reduced to '$out'; the adding of the digits happens inside the innermost loop, with '+' either BEFORE each digit except the first, or AFTER each digit except the last. Since 'all except the last' is easier to calculate ($product>=10, watch those edge cases!), I chose that one.
Also note that, since I'm adding the digits from the right to the left, rather than left-to-right, the addition is reversed. I do not know if that will be an issue. Always consider if reversing the order will save you a lot of work. Obviously, if they NEED to be done in a particular order, then that might be a problem.
The result is:
for ($i=0; $i<500; $i++) {
$product = $i * 3; //Multiply set
print ($i . ' * 3 = ' .$product);
while ($product>10) {
print ' || ';
$out=0;
while ($product>0) {
print ($product%10);
if ($product>=10) {
print " + ";
}
$out+=$product%10;
$product=(integer)($product/10);
}
$product=$out;
print(' = ' .$product);
}
print "<br>";
};
I've decided to add this as a separate answer, because it uses a different approach to answer your question: the least amount of changes to fix the problem, rather than rewriting the code in an easy-to-read way.
There are two problems with your code, which require two separate fixes.
Problem 1: Your code does not add 3 digit (or more) numbers correctly.
If you look carefully at your code, you will notice that you are adding pairs of numbers ($one and $two); each time you add a pair of numbers, you print it out. This means that for the number 102, you are adding 1 and 0, printing out the results, then adding 0 and 2 and printing it out. Look carefully at your results, and you will see that 102 appears twice!
One way to fix this is to use $three and $four (4 digits is enough for 500*3). This is not good programming, because if you later need 5 digits, you will need to and $five, and so forth.
The way to program this is to start with a $sum of zero, then go through each digit, and add it to the sum, thusly:
$ii = 0;
$sum = 0;
while($ii <= $number_of_digits - 1){
$one = intval($addproduct[$ii]);
$sum = $sum + $one;
$ii++;
}
print($i . ' * 3 = ' .$product. ' || ' . $sum . '<br>');
};
The inner if disappears, of course, since it relates to $io, which we are no longer using.
Of course, now you lose your ability to print the individual digits as you are adding them up. If you want those in, and since we don't know in advance how many there are, you would have to keep a record of them. A string would be suitable for that. Here is how I would do it:
$ii = 0;
$sum = 0;
$maths = "";
while($ii <= $number_of_digits-1){
$one = intval($addproduct[$ii]);
if ($maths=="") {
$maths=$one;
} else {
$maths=$maths . " + " .$one;
}
$sum = $sum + $one;
$ii++;
}
print($i . ' * 3 = ' .$product. ' || ' . $maths . " = " . $sum . '<br>');
};
Note the lines with $math in them; there's one at the top, setting it to an empty string. Then, once we've decided on what number we're adding, we add this to $maths. The first time round is a special case, since we don't want "+" before our first digit, so we make an exception - if $maths is empty, we set it to $one; later times around the loop, it's not empty, so we add " + " . $one;
Problem 2: if the result of the addition is more than 1 digit long, go around again. And again, as many times as required.
At this point I would suggest a little refactoring: I would break the print statement into several parts. First the multiplication - that can easily be moved to the top, immediately after the actual multiplication. Printing the <br> can go at the end, immediately before the $i++. This also means you no longer need the else clause - it's already done. This only leaves the ' || ' . $maths . " = " . $sum. This is going to have to happen every time you go through the adding.
Now, replace your if($number_of_digits... with a while($number_of_digits...; this means it goes through as many times as is needed, if it's zero or 100. This does mean that you're going to have to update $product at the end of your loop, with $product = $sum; - put this immediately after the print statement. You will also need to update $number_of_digits; copy the line from the top to the end of the loop.
If you've been following along, you should have:
$i = 1; //Start with one
function count_digit($number) {
return strlen((string) $number);
};
while($i < 500){
$product = $i * 3; //Multiply set
print($i . ' * 3 = ' .$product); // Print basic multiplication
$number_of_digits = count_digit($product); //calls function to count digits of $sum
while ($number_of_digits > 1){ //if $sum has more than one digit add the digits together
$addproduct = strval($product);//seperates the digits of $sum
$ii = 0;
$sum = 0;
$maths = "";
while($ii <= $number_of_digits-1){
$one = intval($addproduct[$ii]);
if ($maths=="") {
$maths=$one;
} else {
$maths=$maths . " + " .$one;
}
$sum = $sum + $one;
$ii++;
}
print(" || " . $maths . " = " . $sum ); // print one lot of adding
$product=$sum;
$number_of_digits = count_digit($product); //calls function to count digits of $sum
};
Print ("<br>"); //go to next line
$i++; //add one
}
I need help creating PHP code to echo and run a function only 30% of the time.
Currently I have code below but it doesn't seem to work.
if (mt_rand(1, 3) == 2)
{
echo '';
theFunctionIWantCalled();
}
Are you trying to echo what the function returns? That would be
if(mt_rand(1,100) <= 30)
{
echo function();
}
What you currently have echoes a blank statement, then executes a function. I also changed the random statement. Since this is only pseudo-random and not true randomness, more options will give you a better chance of hitting it 30% of the time.
If you intended to echo a blank statement, then execute a function,
if(mt_rand(1,100) <= 30)
{
echo '';
function();
}
would be correct. Once again, I've changed the if-statement to make it more evenly distributed. To help insure a more even distribution, you could even do
if(mt_rand(1,10000) <= 3000)
since we aren't dealing with true randomness here. It's entirely possible that the algorithm is choosing one number more than others. As was mentioned in the comments of this question, since the algorithm is random, it could be choosing the same number over, and over, and over again. However, in practice, having more numbers to choose from will most likely result in an even distribution. Having only 3 numbers to choose from can skew the results.
Since you are using rand you can't guarantee it will be called 30% of the time. Where you could instead use modulus which will effectively give you 1/3 of the time, not sure how important this is for you but...
$max = 27;
for($i = 1; $i < $max; $i++){
if($i % 3 == 0){
call_function_here();
}
}
Since modulus does not work with floats you can use fmod, this code should be fairly close you can substitute the total iterations and percent...
$total = 50;
$percent = 0.50;
$calls = $total * $percent;
$interval = $total / $calls;
$called = 0;
$notcalled = 0;
for($i = 0; $i <= $total; $i++){
if(fmod($i, $interval) < 1){
$called++;
echo "Called" . "\n";
}else{
$notcalled++;
echo "Not Called" . "\n";
}
}
echo "Called: " . $called . "\n";
echo "Not Called: " . $notcalled . "\n";
I could never think it would be even challenging but is there any function to calculate a percentage of a number or do I have to write a custom function?
Example:
$result=percent(25,100); //doing the 100%25 operation
$result = 4
function percentage($part, $whole = 100) {
settype($part, "float");
settype($whole, "float");
$formule = ($part / $whole) * 100;
return $formule . " %";
}
echo percentage(25); // returns 25 %
echo percentage(91.8, 176); // returns 52,15909090909091 %
Voila ;-) Could be improved more, but i saw that you figured it out for yourself, so not needed anymore..