intval() PHP function: Convert to integer. Manipulating PHP Data Types
Integer numbers do not have priority over real numbers, but they are destined for a largely “non-digital” purpose. An exact number with a specific number of digits and/or in a specific range of values makes sense for forming CSS rules, can be used as an array key, or unique code database table row records. The integer can be part of a unique code, a password, or checksum when transferring data. An integer is far from being a matter of mathematics and numerical methods; it is often an element of a data or its code.
The meaning of the intval() function
The intval() PHP function is used to convert a “variable to an integer” and has two parameters and a double meaning.
The second parameter is the base of the required number system. Default is decimal system. If you do not specify the second parameter, then a number that begins with the character “0” is considered octal, and those starting with the character “0x” are considered hexadecimal.
The second parameter has a value if the first parameter is a character string.
The last two examples (very large values) show that the result is inappropriate. Essentially, what matters here is the bit capacity of the machine ( operating system). In practice, conversions of such numbers do not make much sense.
The logic behind the PHP intval function is to convert a string or number to an integer for practical application. For example, form CSS rule, which uses only integers. Convert a real number to an integer by simply removing only the integer part.
Using the intval() function
The intval() function in PHP is not the only one for the purpose of getting an integer. You can use round(), ceil() and floor(). These functions operate with generally accepted rounding logic.
The intval() PHP function is devoid of any logic and acts on the principle of getting an integer. If required, then for the right reason the required system Reckoning.
The given examples of intval() PHP show that its main area of application is the logic of the algorithm, and not the logic of calculations.
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 is a numeric value, either an integer or a floating point value.
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 not very convenient format for a person, but, as is known, than simpler presentation data, the faster the computer processes these values. In addition, storing a number in a database is much more cost-effective than using 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 get the current unix timestamp date in 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 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 (from -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 format ISO standard 8601. 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 reverse date conversion from standard format The function is applied to the numeric timestamp value:
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 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";
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 presentation of information, from small to large, could always be described in words, that is, made accessible software processing in one sense or another.
Strings and numbers
Strings are, first of all, collections various characters. In different programming tools fractional part separated from the whole in different ways. Some preferred the period, others the comma (in PHP conversion strings to 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 variables of a specific type (for early-era programs) and the implementation of the modern idea of consensus of all data types means: in PHP, converting a string to a number is the same as doing nothing. IN best case scenario PHP will “cut off”, or more precisely, make it 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 a variable contains only numbers and a period, then a real number can be obtained. 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 representations modern programming. The reverse process has much more varied options. Functions number_format(), printf(), sprintf() can work wonders, not only at the level of a single 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.
I have an application that touches clients 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 text field(usage