# PHP Convert String to Number with Casting and intval

> Convert numeric strings to integers or floats in PHP using dynamic typing, intval(), floatval(), (int)/(float) casting, or the settype() function

**URL:** https://sentry.io/answers/how-do-i-convert-a-string-to-a-number-in-php/

---

## The Problem

How do I convert a string to a number in PHP?

## The Solution

We'll take a look at four ways to convert numeric strings into numbers in PHP:

* Dynamic typing.
* The `intval()` and `floatval()` functions.
* Type casting with `(int)` and `(float)`.
* The `settype()` function.

### Dynamic Typing

PHP is a dynamically typed language that recognizes numerical strings. You can perform mathematical operations directly with numeric strings. When we add `5` to `'3.14'`, we get a float of `8.14` as a result:

```php
$string = '3.14';
$mySum = $string + 5;

var_dump($mySum);
```

Output:

```
// we get a float of 8.14
float(8.14)
```

### The `intval()` and `floatval()` Functions

You can pass a numeric string literal into the `intval()` function to get the integer version or the `floatval()` function to get the float version. For example:

```php
// convert '3.9' to int and float
$myFloat = floatval('3.9');
$myInt = intval('3.9');

// echo out type and value
echo '$myFloat is ',var_dump($myFloat);
echo '$myInt is ',var_dump($myInt);
```

We get an output of `3.9` as our float value. Note how casting a number to an integer won't round it off, as`'3.9'` becomes  `3`:

```
$myFloat is float(3.9)
$myInt is int(3)
```

### Type Casting with `(int)` and `(float)`

Make the `(int)` or `(float)` declaration in front of a numeric string literal to type cast it accordingly. For example:

```php
$castFloat = (float) '3.9';
$castInt = (int) '3.9';

echo '$castFloat is ',var_dump($castFloat);
echo '$castInt is ',var_dump($castInt);
```

Output:

```
$castFloat is float(3.9)
$castInt is int(3)
```

### The `settype()` Function

You can change the data type of the original numeric string into a float or integer using the `settype()` function. This is useful in cases where you don't want to create a new variable to hold a value of a different data type.

In this example, we pass in the variable `$pi` and the datatype `'float'` as arguments into the `settype()` function:

```php
$pi = '3.14';
settype($pi, "float");

var_dump($pi);
```

The `$pi` value is now a float.

```
float(3.14)
```

Here we pass in `'integer'` to change our `$num` variable to an integer:

```php
$num = '4.5';
settype($num, 'integer');

var_dump($num);
```

Output:

```
int(4)
```

---

*Source: [sentry.io/answers/how-do-i-convert-a-string-to-a-number-in-php/](https://sentry.io/answers/how-do-i-convert-a-string-to-a-number-in-php/)*
