PHP | String to Int conversion goes wrong - php

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

Related

Format a decimal number in PHP

I'm trying to format specific numbers up to 8 decimals by deleting unnecessary zeros.
My actual code is:
rtrim(sprintf("%.8f", $upto_eight_decimals), '0')
It actually prevents to format a number as 0.00012 into 1.2E-4 or 0.00012000
However, with numbers integer such as 1 it gets converted into 1. but this point is not my expected result (I know because of rtrim deleting all zeros).
UPDATE: rtrim(rtrim(sprintf("%.8f", $upto_eight_decimals), '0'), '.') it looks like working
You can do it this way, Just use number_format:
$upto_eight_decimals = "0.0001200";
$out = number_format((float)$upto_eight_decimals, 8, '.', '');
echo preg_replace("/\.?0*$/",'',$out);
or
echo $out + 0;
This function returns a string.
This will work for you, let me know is it work or not.

similar_text - string / integer comparing

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.

How to convert a "decimal string" into an integer without the period in PHP

If I have, say, 8.1 saved as a string/plaintext, how can I change that into the integer (that I can do addition with) 81? (I've got to remove the period and change it into an integer. I can't seem to figure it out even though I know it should be simple. Everything I try simply outputs 1.)
You can also try this
$str = '8.1';
$int = filter_var($str, FILTER_SANITIZE_NUMBER_INT);
echo $int; // 81
echo $int+1; // 82
DEMO.
If you're dealing with whole numbers (as you said), you could use the intval function that is built into PHP.
http://php.net/manual/en/function.intval.php
So basically, once you have your string parsed and setup as a whole number you can do something like:
intval("81");
And get back the integer 81.
Example:
$strNum = "81";
$intNum = intval($strNum);
echo $intNum;
// "81"
echo getType($intNum);
// "integer"
Since php does auto-casting, this should work:
<?php
$str="8432.145522";
$val = str_replace('.','', $str);
print $str." : ".$val;
?>
Output:
8432.145522 : 8432145522
Not sure if this will work. But if you always have something.something,(like 1.1 or 4.2), you can multiply by 10 and do intval('string here'). But if you have something.somethingsomething or with more somethings(like 1.42 and 5.234267, etc.), I don't know what to say. Maybe a function to keep multiplying by ten until it's an integer with is_int()?
Sources:
http://php.net/manual/en/function.intval.php
http://php.net/manual/en/function.is-int.php
Convert a string to a double - is this possible?

How do you change a text variable to an int in PHP?

I have a variable that is definited by a POST call from a form where it is inputed into a text field. Is there any way to convert this variable to an interger?
From the form:
Lenght: <input name="length" value="10" type="text" id="lenght" size="2" />
From the php code:
$length = $_POST['lenght'];
$url = substr($url, 0, $length);
This doesn't seem to work and the only reason why I think it isn't working is because $lenght is defined as text and not an interger.
Two things:
It doesn't work because you misspelled length <-> lenght
The correct way to convert a string to an integer is using the function intval.
$length = intval($_POST['length']);
$url = substr($url, 0, $length);
It likely doesn't work because you misspelled length twice, instead of zero or three times.
Seems to be a spelling error in your code: length vs. lenght - that could be your problem right there.
To do an explicit conversion, use the intval() function
$length = intval($_POST['length']);
Ignoring the misspellings of 'length' above, there are a few ways to explicitly convert a string into an integer in PHP. Usually this conversion will happen automatically. Take the following code:
$numeric_string = '42';
echo ($numeric_string * 2);
This will print out "84", as expected. See the reference on Type-Juggling.
If you KNOW that the string you have is a number (perhaps by checking is_numeric()) then you can either cast the variable to an Integer
$numeric_string = '42';
$converted_integer = (int) $numeric_string;
// or
$converted_integer = (integer) $numeric_string;
or use intval()
$numeric_string = '42';
$converted_integer = intval($numeric_string);
An important point to remember about intval() is that it will return a 0 if it can't resolve the string into an Integer. This could (potentially) give you a second way to check for errors (after is_numeric()), or it could cause unexpected results if you aren't properly insuring that the variable is numeric to begin with.
If you are sure that the value you are looking at has a correct representation for the type you want to convert to, you can also use a vanilla type cast operation:
$int = (int) "1"; // var_dump($int) => int(1)
$float = (float) "1.2345"; // var_dump($float) => float(1.2345)
Beware of incorrect representations of the variable that you are converting though, i.e casting "a random string" to a number might not yield the results you expect. If you are handling user input, you're better of using the above suggested solutions with function calls such as intval and floatval
That is because the PHP Web Server uses the name tag instead of the id tag. Even though the id is lenght, the name tag also has to be lenght, or it will malfunction.

In PHP, how do I add to a zero-padded numeric string and preserve the zero padding?

If I have a variable in PHP containing 0001 and I add 1 to it, the result is 2 instead of 0002.
How do I solve this problem?
$foo = sprintf('%04d', $foo + 1);
It would probably help you to understand the PHP data types and how they're affected when you do operations to variables of various types. You say you have "a variable in PHP say 0001", but what type is that variable? Probably a string, "0001", since an integer can't have that value (it's just 1). So when you do this:
echo ("0001" + 1);
...the + operator says, "Hm, that's a string and an integer. I don't know how to add a string and an int. But I DO know how to convert a string INTO an int, and then add two ints together, so let me do that," and then it converts "0001" to 1. Why? Because the PHP rules for converting a string to an integer say that any number of leading zeroes in the string are discarded. Which means that the string "0001" becomes 1.
Then the + says, "Hey, I know how to add 1 and 1. It's 2!" and the output of that statement is 2.
Another option is the str_pad() function.
$text = str_pad($text, 4, '0', STR_PAD_LEFT);
<?php
#how many chars will be in the string
$fill = 6;
#the number
$number = 56;
#with str_pad function the zeros will be added
echo str_pad($number, $fill, '0', STR_PAD_LEFT);
// The result: 000056
?>

Categories