Как string преобразовать в int php
Перейти к содержимому

Как string преобразовать в int php

  • автор:

Как преобразовать в число строку в PHP?

Очень часто нам приходится работать с числовой информацией, которая представлена в виде строк. В результате возникает необходимость в преобразования строки в число. Язык программирования PHP предлагает нам несколько возможностей для этого.

Речь идёт о специальных встроенных в PHP функциях, значительно облегчающих программисту задачу преобразования строки в число. Давайте их рассмотрим.

Преобразование строки в число функцией intval()

Представим, что у нас есть строка, включающая в себя один символ — «2». Вот, как будет выглядеть PHP-код преобразования этой строки в число с помощью встроенной функции intval() :

На выходе получим 2, но уже в виде числа, а не строки.

Давайте пошагово разберём, что же произошло, и расшифруем каждую строчку кода: 1. Объявляется переменная, содержащая строку с символом «1». 2. У нас есть возможность задействовать функцию var_dump() для вывода на экран значения и типа переменной (в ознакомительных целях). 3. Переменная $stringNumberToParse передаётся в функцию intval() в виде аргумента (если речь идёт не о целых числах, используют floatval() ). 4. Функция возвращает нам число, которое мы присваиваем с помощью переменной $parsedInt.

Остаётся добавить, что вышеописанная функция работает в PHP разных версий: 4, 5, 7+.

Преобразование строки в число путём приведения типов

Возможность приведения типов есть во многих языках программирования, и PHP исключением не является. В PHP мы тоже можем поменять тип переменной, применив для этого синтаксис приведения типов: (int)$variable, (float)$variable. Посмотрим, как это выглядит в коде:

Результатом будет следующий вывод:

Итак, что тут происходит: 1. Объявляется переменная, содержащая строку 1. 2. Есть возможность задействовать функцию var_dump() для вывода на экран значения и типа переменной (в ознакомительных целях). 3. С помощью синтаксиса приведения типа для переменной устанавливается префикс (int). 4. Полученное числовое значение присваивается переменной $parsedInt.

Приведение типов можно успешно использовать и в PHP 5 и в PHP 7+.

Преобразование строки в число с помощью settype()

Также для выполнения преобразования можно использовать функцию settype() . Посмотрим, как преобразовать 3-символьную строку «555» в число:

Можно заметить, что параметр $str передается в функциею settype() по ссылке, следовательно, операцию присвоения делать не надо.

В принципе, вышеперечисленных способов вполне хватит для выполнения преобразования строки в число в PHP. Если же хотите знать больше, ждём вас на наших курсах!

How to Convert a String to a Number in PHP

PHP is a weakly typed language. This means that when initializing a variable in PHP, one doesn’t need to declare the variable type. PHP implicitly declares a data type for your variable. This can save you from prospective type errors in your code.

When working with programming languages, it is quite common to want to do things with numbers that are represented as strings. For example, performing arithmetic operations, responding to a client request, feeding the data to a database etc. Even though PHP helps with implicit type conversion in some cases, it is important to know about appropriate methods that can facilitate type conversion.

In this guide, we’ll explore the different ways to convert a string to a number in PHP.

Use the links below to skip ahead in the tutorial:

Background: Types of PHP Numbers

Numbers in PHP can take four forms:

  • Integers
  • Floats
  • Infinity
  • NaN

Here, integers and floats represent the more commonly used number formats in programming languages, and in everyday life. On the other hand, Infinity and NaN are not as well-defined and are more likely to be encountered in edge-cases. Let us look at these in some more depth.

Integers

Integers are the numbers that do not contain a decimal component. They constitute the set Z=<. -3,-2,-1,0,1,2,3..>. If you initialise a variable in PHP as a number that does not have a decimal component, it takes the integer data type (unless it has a value greater than PHP_INT_MAX).

You can verify if a variable is an integer by using the is_int() function, as shown below.

Float numbers are those that contain a decimal component or are represented in an exponential form. These numbers encompass a higher range of numbers, take up more bytes per number, and are precise up to 14 decimal places. Here are some examples of float numbers —

0.08, 2.39, 132.5, 2.0, 1.3e5, 2e10, etc.

It is important to note that arithmetic operations performed between a float number and an integer always return a float number (even if the returned number does not need a decimal part). For example —

You can verify if a variable is a float number by using the is_float() function, as shown below.

PHP INF (Infinity)

‘INF’ in PHP stands for infinity. In programming languages, it is commonly used to represent any number that is greater than the maximum possible float value (which is platform-dependent in PHP).

INF is usually encountered any time you happen to divide an integer or float number by zero.

INF can also be in the negative form, which can be encountered when you perform an operation like log(0) .

You can verify if a variable is INF by using the is_infinite() or is_finite() function as shown below.

PHP NaN

NaN stands for ‘Not a Number’. It represents outputs of mathematical operations that can not be defined. For example, the arc cosine of x, i.e. acos(x) is undefined for x > 1 and x < 1.

You can verify if a variable is NaN by using the is_nan() function as shown below.

Convert a String to a Number Using Type Casting

To convert a PHP string to a number, we can perform type casting using (int) or (float) keywords as shown below.

Similarly, we can also cast PHP strings to float values using (float) .

Using (int) , we can also convert PHP strings that represent float numbers (eg. “1.78”, “18.19”) directly to integers. This operation floors the float number (eg. “18.19”) down to it’s nearest integer (18). For example —

Convert a String to a Number Using intval()

To convert a PHP string to a number, we can also use the intval() or floatval() function. Below are a few examples of intval() ’s usage.

intval() can also be used to convert strings from hexadecimal (base 16) and octal (base 8) number systems to integers of decimal representations (base 10). The intval() function can also use a second parameter that specifies the base for conversion. The default base value is 10 (for decimal representations).

Apart from string to integer conversion, intval() can also be used to convert strings of float numbers to integers.

Similarly, we can use floatval() to convert to float numbers.

Convert a String to a Number Implicitly using Mathematical Operations

If you have a number that is initialized as a string in your code, PHP allows you to perform arithmetic operations directly on that string variable. This means that PHP implicitly performs the type conversion so that your code doesn’t raise an error. These are seemingly some of the advantages of weakly (or loosely) typed languages like PHP.

Let’s see how we can leverage this implicit type conversion to our advantage.

As can be seen above, even though we started with a string variable, a trivial arithmetic operation has implicitly converted it to an integer.

Agreed, this is not the most elegant approach to convert a string to a number, but in many cases, it can still save you from an explicit type conversion.

Formatting Number Strings Using number_format()

Before we close, I’d like to shed some light on how we can format number strings (numbers stored as strings) to improve presentation.

Some posts on the internet incorrectly claim that number_format() function can be used to convert a string to a number. This is not true.

The number_format() function can be used to format numbers that are stored in the form of strings — by adding commas to separate between thousands and/or specifying the number of decimal places. The function always returns a formatted string (not a number variable) and can be used as shown below —

number_format(string_number, n_decimal_places , decimal_point_symbol, separator_symbol)

All arguments here, except the first one ( string_number ) are optional.

Let’s look at a few examples.

Test it for Yourself

In this post, we looked at different types of numbers in PHP — integers, float numbers, INF (infinity), and NaN. We also looked at how we can convert PHP strings into numbers using various methods — by typecasting, using intval() and floatval() methods, and also by implicit conversion using mathematical operations. We also looked at how we can use the number_format() function to format number strings to improve presentation.

Now that you know about numbers in PHP, about how to convert strings to numbers and about number string formatting, go ahead and try it out. Choose whichever conversion method suits you best and implement what you learned in this post.

PHP – How to convert string to int?

In this PHP tutorial, you shall learn how to convert a given string to an integer value using typecasting or intval() function, with example programs.

PHP – Convert String to Integer

To convert string to int in PHP, you can use Type Casting method or PHP built-in function intval().

In this tutorial, we will go through each of these methods and learn how to convert contents of a string to an integer value.

Convert String to Int using Type Casting

To convert string to integer using Type Casting, provide the literal (int) along with parenthesis before the string literal. The expression returns integer value created from this string.

The syntax to type cast string to integer is

Example

In the following program, we take a string with integer content, and convert the string into integer using type casting.

PHP Program

Output

PHP - Convert String to Integer using Type Casting

If the string contains a floating value, then the type casting trims out the decimal part.

In the following program, we take a string $x which contains some decimal value. Then typecast this string to integer and observe the output.

PHP Program

Output

PHP - Convert String to Integer using Type Casting

Convert String to Int using intval()

To convert string to integer using PHP intval() built-in function, pass the string as argument to the function. The function will return the integer value corresponding to the string content.

The syntax to use intval() to convert string to int is

Example

In the following example, we take a string value in $x with integer content, and convert this string into an integer value using intval() function.

PHP Program

Output

PHP - Convert String to Int using intval()

As observed in the type casting method, with intval() function value as well, you get the integer part even if the string contains some decimal point number.

PHP Program

Output

PHP - Convert String to Int using intval()

Conclusion

In this PHP Tutorial, we learned how to convert a string to int using type-casting or intval() function.

How to Convert a String to a Number in PHP

It is possible to convert strings to numbers in PHP with several straightforward methods.

Below, you can find the four handy methods that we recommend you to use.

Applying Type Casting

The first method we recommend you to use is type casting. All you need to do is casting the strings to numeric primitive data types as shown in the example below:

The second method is to implement math operations on the strings. Here is how you can do it:

Using intval() or floatval()

The third way of converting a string to a number is using the intval() or intval() functions. These methods are generally applied for converting a string into matching integer and float values.

Here is an example:

Using number_format

number_format() is a built-in PHP function that is used to format numbers with grouped thousands and/or decimal points. It takes one or more arguments and returns a string representation of the formatted number.

Here’s the basic syntax for the number_format() function:

Let’s take a closer look at each of the arguments:

  • $number : The number you want to format. This can be a float or an integer.
  • $decimals (optional): The number of decimal points you want to include. The default value is 0.
  • $dec_point (optional): The character to use as the decimal point. The default value is «.» (period).
  • $thousands_sep (optional): The character to use as the thousands separator. The default value is «,» (comma).

Here’s an example of how to use number_format() to format a number with two decimal places and a comma as the thousands separator:

In this example, the $number variable contains the number we want to format. We use number_format() to format the number with two decimal places, a period as the decimal point, and a comma as the thousands separator. The resulting string is stored in the $formatted_number variable, which we then output to the screen using echo .

number_format() can be very useful when working with monetary values, where it is common to use a specific format for displaying prices or totals. It can also be used to format other types of numeric data, such as percentages or ratios.

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *