Php number from string to int. Manipulating PHP Data Types
PHP does not require (or support) an explicit type definition when declaring a variable; the type of a variable is determined according to the context in which it is used. That is, if you assign a string value to $var , $var will become a string. If you then assign $var an integer value, it becomes an integer.
An example of automatic type conversion is the addition operator " + ". If any of the operands is a floating point number, then all the operands are interpreted as floating point numbers, the result will also be a floating point number. Otherwise, the operands will be interpreted as integers and the result will also be an integer. Note that this DOES NOT change the types of the operands themselves, only how they are evaluated Some practical examples:
$foo = "0" ; // $foo is a string (ASCII 48)
$foo += 2 ; // $foo is now an integer (2)
$foo = $foo + 1.3 ; // $foo is now a float (3.3)
$foo = 5 + "10 Little Piggies" ; // $foo is an integer (15)
$foo = 5 + "10 Small Pigs" ; // $foo is an integer (15)
?>
If you want to test any of the examples given in this section, you can use the function var_dump() .
Attention: -1 counts TRUE, like any non-zero (negative or positive) number!
Examples of transformations:
var_dump ((bool) "" ); //bool(false)
var_dump ((bool) 1 ); //bool(true)
var_dump ((bool) - 2 ); //bool(true)
var_dump ((bool) "foo" ); //bool(true)
var_dump ((bool) 2.3e5 ); //bool(true)
var_dump ((bool) array(12 )); //bool(true)
var_dump((bool) array()); //bool(false)
var_dump ((bool) "false" ); //bool(true)
?>
Conversion from Boolean
FALSE is converted to 0 (zero), and TRUE- in 1 (unit).
Conversion from Float
When converting from a floating point number to an integer, the number will be rounded towards zero.
If the float exceeds the limits of the integer (typically +/- 2.15e+9 = 2^31), the result will be undefined because the integer does not have enough precision to return the correct result. In this case, no warning or even remark will be displayed.
Attention! Never convert an unknown fraction to a whole, as this can sometimes give unexpected results, for example:
echo (int) ((0.1 + 0.7 ) * 10 ); // prints 7!
?>
Conversion from String
Conversions from other types
For other types, the conversion behavior to an integer is undefined. Currently the behavior is the same as if the value had first been . However Not Rely on this behavior as it may change without warning.
Boolean ( boolean) meaning TRUE is converted to the string "1" and the value FALSE is represented as "" (empty string). In this way, you can convert values in both directions - from Boolean to string and vice versa.
Integer ( integer) or floating point number ( float) is converted to a string represented by a number consisting of its digits (including the exponent for floating point numbers).
Arrays are always converted to the string "Array" , so you can't display the contents of the array ( array), using echo() or print() to see what it contains. To view a single element you need to do something like echo $arr["foo"] . See below for tips on how to display/view all content.
Objects are always converted to the string "Object" . If you want to print the value of an object's member variable ( object) For debugging purposes, read the following paragraphs. If you want to get the class name of the required object, use get_class() .
Resources are always converted to strings with the structure "Resource id #1" , where 1 is unique number resource ( resource) assigned to it by PHP at runtime. If you want to get the resource type, use .
NULL is always converted to the empty string.
Printing arrays, objects, or resources does not provide you with any useful information about the meanings themselves. A better way to output values for debugging is to use functions print_r() And var_dump() .
You can also convert PHP values into strings for permanent storage. This method is called serialization and can be done using the function serialize(). In addition, if in your PHP installation There is WDDX support, you can serialize PHP values into XML structures.
Conversion to Array type
For any of the types: integer, float, string, boolean And resource if you convert the value to an array, you will end up with an array with one element (at index 0) being the scalar value you started with.
If you convert an object to an array ( object), you will get the properties (member variables) of this object as array elements. The keys will be the names of the member variables.
If you convert the value to an array NULL, you will get an empty array.
Conversion to Object type
If an object is converted to an object, it is not modified. If a value of any other type is converted to an object, a new instance of the built-in class stdClass is created. If the value was empty, the new instance will also be empty. For any other value, it will be contained in a scalar member variable:
$obj = (object) "ciao" ;
echo $obj -> scalar ; // will print "ciao"
?>
Information has always been represented by symbols. Only when programming appeared did it partially become letters, numbers and signs (in the formal sense).
Until a certain time, the most popular were oral speech, hand-made symbols, gestures, as well as works of art, in particular. It is important that all these options for the natural representation of information, from small to large, could always be described in words, that is, made accessible to software processing in one sense or another.
Strings and numbers
Strings are, first of all, collections various characters. IN different means programming fraction separated from the whole in different ways. Some preferred a period, others a comma (in PHP, converting a string to a number implies "."). Triads were separated by a single apostrophe, comma, or space. Real numbers were written with the letter "E".
All these are formalities. Mathematics and the principles of operation of any processor have always recognized numbers without frills, and corresponding additional processors have been developed to work with real values.
But the world of concrete type variables (for early era programs) and implementation modern idea consensus of all data types means: in PHP, converting a string to a number is the same as doing nothing. In the best case, PHP will “cut off”, or rather, make 0 or a number, if there is at least one digit in the source string. All digits up to the first non-digit character will add up to this number.
General conversion rule
In PHP, the conversion of a string to a number, unless the programmer has specified otherwise, occurs automatically at the time of application. If the variable contains only numbers and a period, then it can be obtained real number. If a comma is encountered in a sequence of numbers, then everything that comes before it will be interpreted as a number, naturally, an integer.
Any non-numeric character in the sequence of numbers stops the process, and the result of PHP's string-to-number conversion will be only the value that formed before the first non-numeric character.
Mathematics and symbol processing
What is more difficult, the first or the second, even from the standpoint of formulas that do not fit on the page, impressive matrices, graphs that sometimes even the authors cannot untangle, derivatives of integrals, differentials of integrals and polynomials in the nth generation, it is very simple to say: society , of course, honors the merits of mathematics and mathematicians, but the processing of symbols is more important, more complex and covers mathematics like a duvet, providing an inquisitive mind that cannot go beyond the magic of numbers, a favorable environment for creativity.
Usually on PHP string is converted to a number automatically, but it's never a bad idea to check this. It's best to always be sure that PHP correctly understands that a given variable is a number. If there is even a shadow of doubt, you should explicitly specify the type of the variable (int) or (float) before the value and check how PHP understands the type variable functions is_integer() or is_float().
Modern programming trends
The classic interpretation of the PHP “string to number” problem lies within the concepts of modern programming. The reverse process has much more varied options. Functions number_format(), printf(), sprintf() can work wonders, not only at the level of one number, but also at a group of numbers.
Conversion to PHP" line to number" indicates, rather, that we can do this too, but m mathematics and numerical calculations are not our strong point.
Writing decent and reliable functionality that implements this or that number processing in PHP is not a problem, and the result will not be any worse than the result from more mathematical languages. PHP is, first of all, a server language, a language for processing information, including mathematical information.
Among various programming tasks, various manipulations with date and time values are quite common. Rare automated system, the database can do without storing information about the time of a particular process. In addition to the simplest addition of a date to a database record or displaying this date, there are many tasks of displaying these dates in in various forms, checking whether the current time matches set timer, calculating the period between two dates and much more.
To make working with dates easier, each programming language has its own special data types for storing date and time values. Most often this numeric value, either integer or floating point.
IN PHP work with a date, it most often encounters UNIX TIMESTAMP. Here the time is stored as an integer. The calculation of time begins on January 1, 1970. Therefore, for example, the date and time 12/11/2014 19:40:00 would be represented by the number 1418316000. This number shows how many seconds have passed since the zero date of January 1, 1970, called the Unix Epoch.
An example of a PHP page that provides data conversion capabilities is presented on the website in the programs section with the program "Convert date and time format". Here you can generate the desired date in the UNIX TIMESTAMP format, as well as bring this format into a standard, human-readable form.
Getting current time and date in PHP
To get the current server time, use the function
int time(void)
which will return the value in unix timestamp format.
echo time(); // output the current time in unix timestamp format
At first glance, the format is not very convenient for humans, but, as you know, the simpler the data presentation, the faster the computer processes these values. Also, storing a number in a database is much more cost effective than any special format. Also, PHP works the same over time on both Unix and Windows platform, which makes it possible to use the code on any of these platforms.
Convert date and time format in PHP
The simplest mechanism for converting a numeric date value into more understandable values is provided by the function:
array getdate()
She returns associative array, containing date information. If the timestamp parameter is not specified, the current time will be returned. This array contains the following values:
The resulting array allows you to display the values in the desired form:
$date = 1418372345;
$date_mas = getdate($date);
echo $date_mas["mday" ] . " . " . $date_mas["mon" ] . " . " . $date_mas["year" ]; // 12.12.2014
You can also use the function to convert the date and time format:
string date(string $template [, int $unix_timestamp])
It is designed to obtain the current unix timestamp date in the required format. The $template string parameter specifies the output format. The $unix_timestamp parameter can be used to specify which time value to work with. It is optional, so if it is not specified it will be used The current date and time.
The format is specified by the following values:
a | "before" and "after" noon: "am" or "pm" |
A | "before" and "after" noon in capital letters: "AM" or "PM" |
d | day of the month in 2 digits (if less than 10, zero comes first) (01 to 31) |
D | day of the week in 3 letters. For example, "Mon" (Monday) |
j | day of the month, 1-2 digits without leading zeros (from 1 to 31) |
F | name of the month. For example, "January" |
h | hour, 12-hour format (01 to 12) |
H | hour, 24-hour format (00 to 23) |
g | hour, 12-hour format without zeros (1 to 12) |
G | hour, 24-hour format without zeros (0 to 23) |
i | minutes (00 to 59) |
I (capital i) | 1 if daylight saving time is in effect, otherwise 0 |
L | 1 if the year is a leap year, or 0 if it is not a leap year |
B | time in Internet time format ( alternative system time of day countdown) (from 000 to 999) |
T | computer time zone. For example, MDT |
l (lowercase L) | day of the week. For example, "Monday" |
m | month, two digits with zeros (01 to 12) |
n | month, one or two digits without zeros (from 1 to 12) |
M | abbreviated name of the month. For example, "Jan" |
t | number of days in the specified month (from 28 to 31) |
s | seconds (0 to 59) |
S | English two-letter ordinal number suffix ("st", "nd", "rd" or "th") |
U | integer number of seconds since the start of the UNIX epoch |
y | year, digital, 2 digits (14) |
Y | year, digital, 4 digits (2014) |
z | ordinal number of the day in the year (from 0 to 365) |
Z | time zone offset in seconds (-43200 to 43200) |
N | serial number days of the week from 1 (Monday) to 7 (Sunday) in accordance with the ISO-8601 standard, (added to PHP versions 5.1.0) |
w | serial number of the day of the week from 0 (Sunday) to 6 (Saturday) |
W | serial number of the week of the year in accordance with the ISO-8601 standard; weeks start on Monday (added in PHP 4.1.0) |
o | year number according to ISO-8601 standard. Has the same meaning as Y, except when the ISO week number (W) is from the previous or following year; then the year of that week will be used. (added in PHP 5.1.0) |
e | time zone scale code. For example: UTC, GMT, Atlantic/Azores (added in PHP 5.1.0) |
O | difference with Greenwich time, in hours. For example: +0200 |
P | difference from Greenwich Mean Time with a colon between hours and minutes. For example: +02:00 (added in PHP 5.1.3) |
c | date in ISO 8601 standard format. For example, 2014-12-12T15:19:21+00:00 (added in PHP 5) |
r | date in » RFC 2822 format. For example: Thu, 21 Dec 2000 16:01:07 +0200 |
U | number of seconds that have passed since the beginning of the Unix Epoch (The Unix Epoch, January 1, 1970 00:00:00 GMT) |
As you can see from the list, you can get a lot of useful date data using this function. For example:
$date = 1418372345; // initial date and time 12/12/2014 11:19:05
echo date("d.m.Y" , $date); // 12.12.2014 (date)
echo date("H:i:s" , $date); // 11:19:05 (time)
echo date("H:i" , $date); // 11:19 (time)
echo date("t" , $date); // 31 (number of days in a month)
echo date("z" , $date); // 345 (ordinal number of the day in the year)
echo date("l dS \of F Y h:i:s A" , $date); // Friday 12th of December 2014 11:19:05 AM
Other characters included in the pattern will be printed as is on the line. If you need to enter a character that is used in a function as a format code, the “\” character is inserted in front of them. For the value "\n" (the transition character new line), you should specify "\\n". Thus, you can output an entire message containing date and time information:
echo date( "Today z-th day Y year", $date); // Today is the 345th day of 2014
Convert date and time to timestamp format
To convert a date back from a standard format to a numeric timestamp value, use the function:
int mktime(]]]]]])
The mktime() function returns the Unix time value corresponding to the date and time specified by its arguments. For example:
$my_date = mktime(10, 30, 0, 12, 12, 2014);
You should be careful about the order of the function arguments: hours, minutes, seconds, month, day, year.
In addition to simply generating a date value into a timestamp, the mktime() function can be used to perform arithmetically with dates. To do this, you can simply enter the necessary arguments. For example, if you specify the 14th month, then in the final value the month will be the 2nd, and the year value will increase by one:
$my_day = 12;
$my_month = 12;
$my_year = 2014;
$new_date = mktime(0, 0, 0, $my_month + 5, $my_day, $my_year);
echo date("d.m.Y" , $new_date); // 05/12/2015 (date)
You can do the same with other parameters.
Checking date validity in PHP
When working with dates, especially when generating a date using the mktime() function proposed above, it is necessary to take into account the correctness of the entered date. To do this, PHP uses the function:
bool checkdate(int month, int day, int year)
Returns true if the date specified by the arguments is correct; otherwise it returns false. The date is considered correct if:
Year in the range from 1 to 32767;
Month ranges from 1 to 12;
The day for a given month, taking into account leap years, is indicated correctly.
Date checking example:
$my_day = 32;
$my_month = 12;
$my_year = 2014;
if (!checkdate($my_month, $my_day, $my_year))
echo "Error: the date is incorrect";
I have an application that touches clients from all over the world, and naturally I want everything that goes into my databases to be UTF-8 encoded.
The main problem for me is that I don't know what the source encoding of any string will be - it could be from a text field (using