echo 246810121416182022242628303234363840;
such
then it shows me value on brower as
2.4681012141618E+35
Please suggest me solution
wrap it in ""
echo "246810121416182022242628303234363840"
Use number_format(). For example:
echo number_format(246810121416182022242628303234363840,0,null,'');
Also, you can define custom thousands separator.
When dealing with very long integers in PHP, you're going to have trouble regardless of what you try to do.
From PHP's docs
If PHP encounters a number beyond the bounds of the integer type, it will be interpreted as a float instead.
When given an int with value 246810121416182022242628303234363840, PHP interprets it as a float with value 2.4681012141618E+35. Even attempting to use number_format() as Timur suggests will result in printing '246810121416182028912708947168722944'.
Given that PHP can't be passing that value as you describe, you must be typing it in your code? If this is the case, your best bet for accurate echoing is to create a string instead of an int.
Related
I have made various functions such as "get_current_balance_from_my_bank_account()". It technically returns a string, but it's always a full integer number (as a string) which has never caused problems when its return variable is used directly in calculations.
However, it feels wrong.
Should I be doing something like this?
return (int)$amount_as_a_string;
Instead of the current:
return $amount_as_a_string;
? Or is (int) some archaic/legacy way of doing this? Should I be using some other, better method?
Example of the context:
$my_balance = get_current_balance_from_my_bank_account();
$previous_balance = load_last_balance();
echo 'I have ' . format_money_prettily($my_balance - $previous_balance) . '!' . PHP_EOL;
Again, I rarely if ever run into issues with this because it understands the "real" type. It does still feel wrong that I'm technically returning and sending around strings which in theory could be causing problems sooner or later -- perhaps catastrophic ones in production!
PHP will implicitly type cast in many situations, but not all. Take for example this:
echo json_encode(['balance' => get_current_balance_from_my_bank_account()]);
Now your type propagates to some other system via JSON, where it may cause actual issues if that system isn't so lenient about types. You're making somebody else deal with your incorrect type.
So, yes, your function should always return the type that it claims it returns. PHP implicitly "helping" you when you don't stick to your own type declarations is just sweeping the problem in the rug, but the problem is still there and may eventually cause actual issues.
I don't think that is something you have to worry to much, considering that php has automatic type conversion.
From the docs:
PHP does not require (or support) explicit type definition in variable declaration; a variable's type is determined by the context
in which the variable is used.
Just because the function returns the right data type does not mean that the value is correct or what you expect.
If you want to make sure that the function returns ok value, validating it before returning it much more helpful than simply typecasting it to correct type.
If you want to be more explicit about typing in PHP, have a look at the following from the manual:
default
By default, PHP will coerce values of the wrong type into the expected scalar type if possible.
For example, a function that is given an integer for a parameter that expects a string will get a variable of type string.
Strict mode
It is possible to enable strict mode on a per-file basis. In strict mode, only a variable of exact type of the type declaration will be accepted, or a TypeError will be thrown.
The only exception to this rule is that an integer may be given to a function expecting a float.
Function calls from within internal functions will not be affected by the strict_types declaration.
To enable strict mode, the declare statement is used with the strict_types declaration:
<?php
declare(strict_types=1); // strict type declaration MUST be the very first statement in your script
function sum(int $a, int $b) {
return $a + $b;
}
var_dump(sum(1, 2));
var_dump(sum(1.5, 2.5));
?>
output
int(3)
Fatal error: Uncaught TypeError: Argument 1 passed to sum() must be of the type integer, float given
Note: Enabling strict mode will also affect return type declarations.
source: php.net
This will never be required in PHP, as it does the type conversion by itself. However you can do this if you want. This depends from project to project, but sometimes a decision is made for a certain project to use explicit types where possible. Also this is a good practice if you are working on a team where some of the people are comfortable with more strict languages.
In your case, depending on the number, there might be a good side in keeping it as a string, as if you convert it to int via casting and the number is bigger than the max_int_size, it will overflow.
As for the other question, casting as int (int) or (integer) is a perfectly good way to do it, even in newer versions. It is not a legacy way whatsoever. This does not mean there aren't other good ways to do that, though. You can also use something like intval() or settype(). In my opinion there isn't one right way to do it. You can decide for yourself on how to do that.
if i use:
socket_read($socket, 1024);
I don't know what type of variable it returns. I want to make it to an int, but i don't know how.
The Server respons only a number (35).
If i echo it, i get 35. If i cast it to "(int)" i get 0. intval returns 0 too.
I have tried to cast it to string, and pick the first letter (3) but it returned 0. Substr doesn't work too.
I want to have an int value, so that i can calculate things with this value. I need an int to calculate the prozentage of this value from another value.
What can i do?
EDIT:
Fixed it in JAVA SERVER SOCKET CODE whith:
PrintWriter out = new PrintWriter(server.getOutputStream());
instead of using
DataOutputStream out = new DataOutputStream(server.getOutputStream());
Why not read the manual page. It returns a string.
Try print_r to find out the details of that string. Might be in binary?!
As you can see in the manual, socket_read always returns a string. You should try using var_dump() to check the real value of the variable.
Did you try to sum any number to that variable? In the autocast it may work.
Seems like the string contains additional whitespace that prevents PHP from converting it to a number.
Therefore I suggest you use the trim() function to remove whitespace before converting it to a number. Or you could use a regular expression to remove all non-numeric characters $out = preg_replace("/[^0-9]/g", "", $in)
If this still doesn't work and var_dump doesn't help you either, I'd suggest to sniff the network traffic using WireShark to inspect the packet coming from the server. If you're in control of what the server sends, use a decent serialization method like XML or JSON instead of inventing some protocol yourself.
Even being relatively well aware of PHP peculiarities, the following strange behaviour still got me confused today:
// loose
$a = array(true => 'foo');
var_dump(array_key_exists(1, $a));
// strict
$a = array('7.1' => 'foo');
var_dump(array_key_exists('7.10', $a));
I wonder what could be the technical reason of this effect, so the question is, what in the process behind this function is causing values of some types to be compared loosely while others are compared strictly? I'm not complaining about the behaviour, but trying to understand that, so there is no point for "PHP sucks" comments.
In your first case, a boolean value is not a valid array key, so it is immediately turned into a 1 when you initialize the array, making your search match.
In your second case, the array key is a string, and '7.1' is not the same string as '7.10'
In your second example, '7.1' and '7.10' are strings. They are compared as string, so they don't match.
Now why do you have a match in the first example? Array keys can be either strings or integer. So true is converted to integer, which evaluates as 1.
This is documented here. Note that, keys are integers or strings. Specific key casts are mentioned in the documentation, in particular (for your case) that bools are cast to integers (ie. true as 1 and false as 0). As noted elsewhere, your other examples are strings (remove the quotes to make them floats, which would then be truncated to integers as per the docs).
maybe you could add the script output there? First glance though: Boolean as array key? I dont think thats gonna help in any way! 2nd: 7.10 is not the same at 7.1 - declaring this in '' makes it a string....
if you want true as a keyname, then you need to encapsulate it in either single or double quotes. IF you dont know about PHP and single/double quotes, it will cause the contents to be treated as a string value rather than Integer of Boolean (True/False)
I am wondering, If I have a value I know should be numeric, is multiplying it by 1 a safe method to clean it?
function x($p1){
$p1*=1;
sql="select * from t where id ={$p1}";
//run query..
}
Although my example uses an ID, this is being used for many types of numeric values I have in my app (can be money, can be pai etc).
I don't see why it wouldn't be. But what's wrong with using prepared statements? That's always going to be safer than using PHP variables directly in SQL statements.
You can use is_numeric()
I'm sure there is a more "appropriate" way, but for the scope of your question, I would say yes. If some sort of string is passed PHP will interpret it as a zero when doing the mathematical operation.
You can also use is_int()
While that'll probably work, intval seems like a better solution. http://php.net/manual/en/function.intval.php. Your intent will likely be more obvious to someone else reading your code.
If you want to check if a value is numeric before converting it to an int, use is_numeric ( http://php.net/manual/en/function.is-numeric.php ). It'll check for strings that are numeric as well as integers. For example, if a number was coming back from a text input form via AJAX, it might be a string. In that case, is_int would return false, but is_numeric would return true.
EDIT
Now that I know you use DECIMAL for the MySQL column type, you can do something like this:
function getItem($pValue)
{
if (!is_numeric($pValue))
{
return false;
}
$Query = sprintf
(
'SELECT * FROM %s WHERE %s = %.2f',
'TableName',
'Price',
$pValue
);
// Do something with $Query
}
It works most of the times as it will cast strings to integers or doubles, but you have to be careful. It's going to work correctly for scalar values. However, if you do this:
x(new stdClass);
You'll get an E_NOTICE. This is not so bad, right? This:
x(array());
And you'll get an E_ERROR, Unsupported operand types, and the script terminates.
Maybe you'd think that it isn't so bad, but a fatal error at an inopportune moment can leave your system in an unstable state, per example, by losing referential integrity or leaving a series of queries unfinished.
Only you knows if a case like the above can happen. But if this data comes from a user in any way, I'd go with Murphy's Law on this one and not trust it.
I've just decided to venture off into PHP land for fun and to learn, reading that php is loosely typed and that $var's can be reused is this true that the code below will pose no problem?
$x = 996;
$x = mysql_query("SELECT aString FROM table1");
the variable x will stored as an int datatype with 996, then after the second line it will stored as a string datatype with the string from the query?
There wont be any casting errors?
You are correct; that's the definition of being "loosely typed". However, that may not be the best practice.
http://drupaler.co.uk/blog/baby-dont-you-loose-your-type-me/66 is a good read on your subject.
There will be no errors, except that the second line won't give you a string, mysql_query returns an internal PHP type called a resource (generally some kind of opaque handle/pointer for library functions)
There wont be any casting errors?
Correct!
jalf explained it well here