Parsing string to int in php

Converting a String to an Integer in PHP

This blog explores the world of PHP and examines the different approaches one can take to convert strings to integers. The significance of type conversion and its relevance in PHP programming is introduced at the outset. The blog covers five distinct techniques for converting strings to integers, including the utilization of the (int) cast operator, the intval() function, the filter_var() function, the sscanf() function, and the utilization of mathematical operations.

Introduction:

In PHP, type conversion is an essential aspect of programming when dealing with different data types. In this blog, we will explore multiple methods to achieve this conversion, discussing their pros, cons, and usage scenarios.

Method 1: Using the (int) Cast Operator

The most straightforward method to convert a string to an integer in PHP is by utilizing the (int) cast operator. This operator allows us to explicitly specify the desired data type. By enclosing the string variable within parentheses and preceding it with (int), we can achieve the conversion. For example:

$stringNumber = "42"; $integerNumber = (int)$stringNumber; echo $integerNumber; // Output: 42 

Method 2: Using the intval() Function

Another popular method to convert strings to integers in PHP is by using the intval() function. This function takes a variable as an argument and attempts to convert it to an integer. If the conversion fails, it returns 0. For example:

$stringNumber = "42"; $integerNumber = intval($stringNumber); echo $integerNumber; // Output: 42 

Method 3: Utilizing the filter_var() Function

PHP provides the filter_var() function, which offers powerful data filtering capabilities. This function can also be utilized to convert strings to integers by applying the FILTER_VALIDATE_INT filter. Here’s an example:

$stringNumber = "42"; $integerNumber = filter_var($stringNumber, FILTER_VALIDATE_INT); echo $integerNumber; // Output: 42 

Method 4: Using the sscanf() Function

The sscanf() function allows parsing input strings based on a specified format. By using the «%d» format specifier, we can extract an integer from a string. Here’s an example:

$stringNumber = "42"; sscanf($stringNumber, "%d", $integerNumber); echo $integerNumber; // Output: 42 

Method 5: Leveraging Mathematical Operations

An unconventional but valid method for converting strings to integers involves performing mathematical operations on the string. PHP automatically converts strings to numbers when used in arithmetic operations. Here’s an example:

$stringNumber = "42"; $integerNumber = $stringNumber + 0; echo $integerNumber; // Output: 42 

Conclusion:

In PHP, converting strings to integers is a common task in various programming scenarios. This blog explored five different methods for accomplishing this conversion: using the (int) cast operator, the intval() function, the filter_var() function, the sscanf() function, and leveraging mathematical operations.

Читайте также:  Php код специального символа

Related Post

Источник

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

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

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

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

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

 
$stringNumberToParse = "2"; // var_dump($stringNumberToParse); // string '2' (length=1) // Convert the string to type int $parsedInt = intval($stringNumberToParse); // var_dump(is_int($parsedInt)); // boolean true // var_dump($parsedInt); // int 2 echo $parsedInt;

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

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

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

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

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

 
$stringNumberToParse = "2"; //var_dump($stringNumberToParse); // string '2' (length=1) // Convert the string to type int $parsedInt = (int)$stringNumberToParse; //var_dump(is_int($parsedInt)); // boolean true //var_dump($parsedInt); // int 2 echo $parsedInt;

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

Итак, что тут происходит: 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 into a number using PHP

In most programming languages, it is a requirement to specify the data type that a variable should hold before using the variable. These data types include char, string, int, double, float, array, boolean, etc.

Some programming languages are not so strict and thus you don't have to specify which data type it should store eg. Javascript and PHP.

For instance, in JavaScript, all you have to do is use the keywords var or let before the variable name.

In PHP, all you have to do is write a dollar sign $ followed by the variable name without having to specify the type.

However, by default, if the value of a variable is enclosed with quotes (single or double), it is considered as a string and in some languages, it will not give the desired results when used in arithmetic operations.

Example in Javascript

As you can see, in Javascript the two variables are treated as strings and their values were concatenated instead of an addition to take place. So in Javascript, you must not define numeric variables with values enclosed within quotes. Else, you will have to first use the parseInt() to convert the string into integer type or parseFloat() to convert the string into a float before attempting to perform arithmetic operations.

In a similar way, PHP treats every value enclosed within quotes as a string. Let's compare two numbers, one enclosed in quotes, and the other without.

Example

num1 and num2 are not identical

$num1 is considered a string while $num2 is considered an integer therefore not identical.

In PHP, we can check the data type of a variable using either the gettype() or the var_dump() function.

Example

num1 is a string
num2 is integer

However, in PHP, unlike Javascript, you can add two numbers when one is of integer type and the other a string (or both are strings) without any problem.

Example

The output is of integer type.

While strings in PHP can be converted to numbers (ie, int, float, or double) very easily, in most cases it won’t be required since PHP automatically does implicit type conversion at the time of using variables.

However, there are some instances where it may not be a good idea to wait for PHP to do the conversion for you.

For example on a parameterized PDO query, there will be a struggle sometimes for the parser to realize it is a number and not a string, and then you end up with a 0 in an integer field because you did not cast the string to an int in the parameter step.

Another scenario is when you are sending data in JSON format via an API to an app that expects it to be a number, and that is built in a language that doesn't do implicit type conversion. This will result in an error.

Due to these, among other reasons and scenarios, you may want to do type conversion explicitly.

Methods of string to number conversion in PHP

There are multiple ways in which you can do explicit type conversion from string to number in PHP as explained below.

1. Using the settype() function

The settype() function is used to convert a variable to a specific data type.

Syntax

Parameters

Example

"; echo "The num2 type is ".gettype($num2); 

The num1 type is integer
The num2 type is double

2. Using the identity arithmetic operator

There is a little-known about and rarely used arithmetic operator in PHP called "identity", used for converting a numeric string to a number.

Syntax

All you have to do is place a plus sign + before the string numeric variable or value. It converts the number to a float and an int value.

Example

3. Cast the strings to numeric primitive data types

Typecasting is the conversion of data from one data type to another data type. You can use (int) or (integer) to cast a numeric string to an integer, or use (float), (double), or (real) to cast a numeric string to float. Similarly, you can use the (string) to cast a variable to string, and so on.

Example

"; echo "The num2 type is ".gettype($num2); 

The num1 type is integer
The num2 type is double

4. Perform math operations on the strings

In PHP, performing mathematical operations converts a numeric string to an integer or float implicitly.

You can perform operations such as ceil(), round() or floor(). However, these will round the number up or down. If you don't want to change the value then do as below.

You can easily convert a string to a number by performing an arithmetic operation that won't change the value such as addition with a zero (0) or multiplication by one (1).

Example

"; echo "The num2 type is ".gettype($num2); 

The num1 type is integer
The num2 type is double

5. Use intval() or floatval()

These functions intval() and floatval() can also be used to convert a numeric string into its corresponding integer and float value respectively.

Example

An advantage of this method is that you can convert multiple numeric strings in an array at once using the array_map() function which you can't do with the other methods.

Example

array(6) < [0]=>int(23) [1]=> int(14) [2]=> int(33) [3]=> int(76) [4]=> int(29) [5]=> int(54) >
array(5) < [0]=>float(3.142) [1]=> float(10.12) [2]=> float(92.01) [3]=> float(25.98) [4]=> float(54.37) >

It's my hope that now you can comfortably do data conversion from strings to numbers explicitly in PHP.

  • Creating and working with Strings in PHP
  • How to make multi-line Strings in PHP
  • How to check whether a String is empty in PHP
  • How to remove all spaces from a String in PHP
  • How to remove special characters from a String in PHP
  • How to do String to Array conversion in PHP
  • How to do Array to String conversion in PHP
  • How to check if a string contains a certain word/text in PHP
  • How to replace occurrences of a word or phrase in PHP string
  • Regex to remove an HTML tag and its content from PHP string
  • Variables, arrays and objects interpolation in PHP strings
  • How to insert a dash after every nth character in PHP string
  • How to change case in PHP strings to upper, lower, sentence, etc
  • Counting the number of characters or words in a PHP string

Источник

Оцените статью