[PHP] How to convert from strings to numbers

PHP PHP
Mainly articles about PHP

This article describes how to convert from strings to numbers in PHP.
PHP is a dynamically typed language, meaning that there is no need to declare the data type of a variable.
Therefore, string to numeric conversions are often used.
This article is intended for beginner to intermediate engineers.

About Data Types in PHP

PHP has a variety of data types. Among them, the main data types used in this article are as follows:

  • String
  • Integer
  • Float

How to convert from a string to an integer value

In PHP, there are several ways to convert from strings to integer values.

How to use the intval function

The intval function is used to convert a string to an integer value.
For example, it can be used in the following code:

$str = "123";
$int = intval($str);
echo $int;
PHP

In this case, the string "123" is converted to the integer "123" and assigned to the variable $int.

How to use typecasting

(int) to cast a string to an integer type.
See the example below:

$str = "456";
$int = (int)$str;
echo $int;
PHP

Again, the string "456" is converted to the integer "456" and assigned to the variable $int.

How to convert from strings to floating point numbers

Next, we will explain how to convert from strings to floating point numbers in PHP.
Here, too, there are two methods.

How to use the floatval function

The floatval function is used to convert a string to a floating-point number.
It can be used in code like the following:

$str = "3.14";
$float = floatval($str);
echo $float;
PHP

In this case, the string "3.14" is converted to the floating-point number "3.14" and assigned to the variable $float.

How to use typecasting

(float) to cast a string to a floating-point number type.
See the example below:

$str = "1.23";
$float = (float)$str;
echo $float;
PHP

Again, the string "1.23" is converted to the floating-point number "1.23" and assigned to the variable $float.

Summary

This article explains how to convert from strings to numbers in PHP.
When converting from a string to an integer, you can use the intval function or type casting.
When converting from strings to floating point numbers, floatval functions or type casting can be used.
Either method can be used to easily convert from strings to numbers.

Follow me!

コメント

PAGE TOP
Copied title and URL