similar_text - string / integer comparing - php

it's my first post here, so welcome everyone!
I'm trying to write a rule to simply protect my website against flooding by users posting it's content. I decided to use similar_text() function in PHP to compare strings (last added string by user and the one that one is adding at the moment), calculate similarity (%) and if the result is too high (similar in more than 90%) the script will not add a record to database.
Here is what I have:
similar_text($last_record, $new_record, $sim);
$similarity = (int) number_format($sim, 0);
if ($similarity < 90)
{
// add the record
}
else
{
// dont add anything
}
The problem is with this: if ($similarity < 90). I format the number and then convert it from string to int value, but the script doesn't care.
When I use quotas it works: if ($similarity < "90"). The question is why script doesn't work when I use the value as an integer value and it works when I use it as a string?

number_format returns a string where you need an int. So a string comparison to "90" works, but an int comparison fails. You can use int_val to convert to an int.
Also, I'm wondering if maybe you have something else wrong. I took your code sample and ran it locally, and it seems to work just fine even without swapping (int) for int_val.
With the following values:
$last_record = "asdfasdfasdf";
$new_record = "aasdfasdfasdf";
$similarity is 96 and the greater than section of the if triggers.
With these values:
$last_record = "asdfasdfasdf";
$new_record = "fffdfasdfasdf";
$similarity is 80 and the less than section of the if triggers.

Related

PHP | String to Int conversion goes wrong

Hello my dear coding friends.
I have a time, formatted like this 08:00:00. That time comes from my phpMyAdmin database where i have a "time" field and i get that field by using a query in my php code. The variable type of that mysqli variable containing the time is string, so i want to cut the minutes and seconds part off and turn the rest into an integer by adding (int). The code looks like this: Image of code
if (strpos ($meetings["dtStartZeit"], "0") == 0) {
$startTimeString = substr ($meetings["dtStartZeit"], 1, 1);
} else {
$startTimeString = substr ($meetings["dtStartZeit"], 0, 2);
}
$startTimeNumber = (int)$startTimeString;
Now comes the confusing part. If i have a string like this --> "8" and I want to turn it into an integer by using the above mentioned function, the result is 9 and not 8. The even more confusing part is that if I increase the value of that variable by 1, the result is 8.
Can someone explain me this please?
You don't need to use strpos or substr here. Use a single line type cast instead all of your code:
$startTimeNumber = (int) $meetings['dtStartZeit']; // "08:00:00" --> 8
To convert a string to an int you use intval()
because a string is an object of chars casting them wont ever work as expected which is what (int) is doing

How to calculate using a POST variable?

I need to multiply this POST variable by 12. As an example, if the amount was 10, the result should say:
Amount: 120
Here's my code so far:
Amount :'.$_POST['my_amount'].'<br/>
I tried to run the calculation in another variable, but this doesn't seem to work:
$result = ($_POST['my_amount'])*12;
or maybe it works and my output code is not working:
$vl_text='';
Amount :'.$_POST['my_amount'].'<br/>'.;
If you want your output to resemble your first example.,.. Amount:120 your missing chunks in each of the following 3 examples. first ensure that your $_POST variable is a valid one and set it to a new variable so you can print out the variable if you need to ...
// if you only expect $_POST['my_amount'] to contain integers...
if(is_int(intval($_POST['my_amount']))){
$my_amount = intval($_POST['my_amount']) * 12;
// or if you expect $_POST['my_amount'] to possibly contain a decimal
if(is_float(floatval($_POST['my_amount']))){
$my_amount = floatval($_POST['my_amount']) * 12;
intval ensures that a variable is cast as an integer if it can be, while not entirely necessary as multiplying in php will do this...its good practice to check any variables that you are using for and math functionality.
floatval does the same for for numbers with decimal. as an integer has to be a whole number if your variable could numbers that could contain decimals... use floatval
all of your examples then need to specify to print/echo the string....so
// your second line
echo 'Amount :'.$my_amount .'<br/>';
// your fourth line...
$vl_text='Amount: '.$my_amount;
echo $vl_text;
}
The most logical explanation is that you get string from POST. A good way to achieve what you want is to convert the POST value to int but keep in mind that it could not be numerical.
$int = (is_numeric($_POST['my_amount']) ? (int)$_POST['my_amount'] : 0); //If POST value is numeric then convert to int. If it's not numeric then convert it to 0
$_POST['my_amount'] = 150;
$data = $_POST['my_amount'] * 12;
echo $data;
Result will be 1800

PHP Simple Math Results in Unexpected Result

I have two variables in a PHP program for billing statements, $charges and $payments.
$charges is the total amount due before any payments. $payments is the total amount received.
I calculate the balance due like so:
$balance_due = $charges-$payments;
Simple, except I am getting the following result:
$balance_due has -9.0949470177293E-13 for a value (expecting 0).
Both $charges and $payments have a value of 5511.53.
When I var_dump($charges) and var_dump($payments) they both show: float(5511.53)
This code (and === ):
if($charges == $payments){
error_log('they are the same');
}else{
error_log('they are not the same');
}
both result in false.
If I hard code: $charges = $payments = 5511.53; and run it then $balance_due = 0 as expected.
I am confused. What am I missing?
EDIT NOTES
I was able to use a user contributed function by Nitrogen found on the BC Math Functions page that was suggested I look at in order to come up with the following solution:
if(Comp($charges, $payments)===0){
$balance_due = 0;
}else{
$balance_due = ( $charges - $payments );
}
function Comp($Num1,$Num2,$Scale=null) {
// check if they're valid positive numbers, extract the whole numbers and decimals
if(!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num1,$Tmp1)||
!preg_match("/^\+?(\d+)(\.\d+)?$/",$Num2,$Tmp2)) return('0');
// remove leading zeroes from whole numbers
$Num1=ltrim($Tmp1[1],'0');
$Num2=ltrim($Tmp2[1],'0');
// first, we can just check the lengths of the numbers, this can help save processing time
// if $Num1 is longer than $Num2, return 1.. vice versa with the next step.
if(strlen($Num1)>strlen($Num2)) return(1);
else {
if(strlen($Num1)<strlen($Num2)) return(-1);
// if the two numbers are of equal length, we check digit-by-digit
else {
// remove ending zeroes from decimals and remove point
$Dec1=isset($Tmp1[2])?rtrim(substr($Tmp1[2],1),'0'):'';
$Dec2=isset($Tmp2[2])?rtrim(substr($Tmp2[2],1),'0'):'';
// if the user defined $Scale, then make sure we use that only
if($Scale!=null) {
$Dec1=substr($Dec1,0,$Scale);
$Dec2=substr($Dec2,0,$Scale);
}
// calculate the longest length of decimals
$DLen=max(strlen($Dec1),strlen($Dec2));
// append the padded decimals onto the end of the whole numbers
$Num1.=str_pad($Dec1,$DLen,'0');
$Num2.=str_pad($Dec2,$DLen,'0');
// check digit-by-digit, if they have a difference, return 1 or -1 (greater/lower than)
for($i=0;$i<strlen($Num1);$i++) {
if((int)$Num1{$i}>(int)$Num2{$i}) return(1);
else
if((int)$Num1{$i}<(int)$Num2{$i}) return(-1);
}
// if the two numbers have no difference (they're the same).. return 0
return(0);
}
}
}
That solution worked for me. The answer provided by imtheman below also works and seems more efficient so I am going to use that one instead. Is there any reason not to use one or the other of these?
The way I solved this problem when I ran into it was using php's number_format(). From php documentation:
string number_format(float $number [, int $decimals = 0 ])
So what I would do is this:
$balance_due = number_format($charges-$payments, 2);
And that should solve your problem.
Note: number_format() will return a string, so to compare it you must use == (not ===) or cast it back into a (float) before comparison.

PHP if statement fails to validate on "!== 0"

How can the below be possible:
$varnum = 4;
if( $varnum/4 - floor($varnum/4) !== 0){
echo 'foo';
}
This echoes 'foo' on my server running PHP 5.1.6. If i change the operator to == I get the same results.
I have no idea why, but could it possibly be because "==" is "equals" and "!==" is "Not identical"? How then would I make them identical? I guess in javaScript I would "parseInt", but there is no such thing in PHP, right?
The reason this fails is because in PHP, the floor function returns a float, despite the fact that the value is always a whole number. You can see this in the documentation here: http://php.net/manual/en/function.floor.php
You're doing a fixed type comparison of that float to an integer zero, so the result is false, regardless of whether the value is actually zero.
To fix this, either:
cast the output of floor to an integer - either intval(float(...)) or (int)float(..)
use != instead of !==.
use 0.0 instead of just 0 to compare against.
In case you're wondering why floor() would return a float rather than an integer, it's because the input is a float. The float data type has a larger possible range than integer, and thus it is possible to call floor() on a value that would be too big to hold in an integer. Therefore it would not be safe for the function to return an integer; it returns a float instead so that it can guarantee the result will be correct.
It may seem odd at first glance, but hopefully that explains the logic behind it for you.
What is it you are trying to accomplish? If you are trying to see if $varnum is divisible by four then use modulus, so...
$varnum = 4;
if ($varnum % 4 != 0) {
echo "foo - $varnum is divisible by 4";
}
You original post should use '!=' versus '!==', like this:
$varnum = 4;
if( $varnum/4 - floor($varnum/4) != 0){
echo 'foo';
}

How to get a random value from 1~N but excluding several specific values in PHP?

rand(1,N) but excluding array(a,b,c,..),
is there already a built-in function that I don't know or do I have to implement it myself(how?) ?
UPDATE
The qualified solution should have gold performance whether the size of the excluded array is big or not.
No built-in function, but you could do this:
function randWithout($from, $to, array $exceptions) {
sort($exceptions); // lets us use break; in the foreach reliably
$number = rand($from, $to - count($exceptions)); // or mt_rand()
foreach ($exceptions as $exception) {
if ($number >= $exception) {
$number++; // make up for the gap
} else /*if ($number < $exception)*/ {
break;
}
}
return $number;
}
That's off the top of my head, so it could use polishing - but at least you can't end up in an infinite-loop scenario, even hypothetically.
Note: The function breaks if $exceptions exhausts your range - e.g. calling randWithout(1, 2, array(1,2)) or randWithout(1, 2, array(0,1,2,3)) will not yield anything sensible (obviously), but in that case, the returned number will be outside the $from-$to range, so it's easy to catch.
If $exceptions is guaranteed to be sorted already, sort($exceptions); can be removed.
Eye-candy: Somewhat minimalistic visualisation of the algorithm.
I don't think there's such a function built-in ; you'll probably have to code it yourself.
To code this, you have two solutions :
Use a loop, to call rand() or mt_rand() until it returns a correct value
which means calling rand() several times, in the worst case
but this should work OK if N is big, and you don't have many forbidden values.
Build an array that contains only legal values
And use array_rand to pick one value from it
which will work fine if N is small
Depending on exactly what you need, and why, this approach might be an interesting alternative.
$numbers = array_diff(range(1, N), array(a, b, c));
// Either (not a real answer, but could be useful, depending on your circumstances)
shuffle($numbers); // $numbers is now a randomly-sorted array containing all the numbers that interest you
// Or:
$x = $numbers[array_rand($numbers)]; // $x is now a random number selected from the set of numbers you're interested in
So, if you don't need to generate the set of potential numbers each time, but are generating the set once and then picking a bunch of random number from the same set, this could be a good way to go.
The simplest way...
<?php
function rand_except($min, $max, $excepting = array()) {
$num = mt_rand($min, $max);
return in_array($num, $excepting) ? rand_except($min, $max, $excepting) : $num;
}
?>
What you need to do is calculate an array of skipped locations so you can pick a random position in a continuous array of length M = N - #of exceptions and easily map it back to the original array with holes. This will require time and space equal to the skipped array. I don't know php from a hole in the ground so forgive the textual semi-psudo code example.
Make a new array Offset[] the same length as the Exceptions array.
in Offset[i] store the first index in the imagined non-holey array that would have skipped i elements in the original array.
Now to pick a random element. Select a random number, r, in 0..M the number of remaining elements.
Find i such that Offset[i] <= r < Offest[i+i] this is easy with a binary search
Return r + i
Now, that is just a sketch you will need to deal with the ends of the arrays and if things are indexed form 0 or 1 and all that jazz. If you are clever you can actually compute the Offset array on the fly from the original, it is a bit less clear that way though.
Maybe its too late for answer, but I found this piece of code somewhere in my mind when trying to get random data from Database based on random ID excluding some number.
$excludedData = array(); // This is your excluded number
$maxVal = $this->db->count_all_results("game_pertanyaan"); // Get the maximum number based on my database
$randomNum = rand(1, $maxVal); // Make first initiation, I think you can put this directly in the while > in_array paramater, seems working as well, it's up to you
while (in_array($randomNum, $excludedData)) {
$randomNum = rand(1, $maxVal);
}
$randomNum; //Your random number excluding some number you choose
This is the fastest & best performance way to do it :
$all = range($Min,$Max);
$diff = array_diff($all,$Exclude);
shuffle($diff );
$data = array_slice($diff,0,$quantity);

Categories