Encodera

Thanks for reading!

Donate to the site — we work hard for you.

PHP reference

intval

Converts a value to an integer.

Syntax

intval(mixed $value, int $base = 10): int

Parameters

ParameterTypeDescription
$valuemixedA string, a number or a boolean.
$baseintOptional. The base for strings.

Return value

intAn integer; `0` if the conversion failed.

Examples

A string, a fraction and text:

<?php
 
echo intval('42'), "\n";
echo intval(7.9), "\n";
echo intval('12 apples'), "\n";
echo intval('apples');

Output:

42
7
12
0

The (int) cast does the same:

<?php
 
echo (int) '42' + 1;

Output:

43

Notes

The fraction is dropped, not rounded. A non-numeric string silently becomes 0 — if that is an error, check the value with is_numeric() first.

See also

  • is_numeric — Checks whether a value is a number or a numeric string.
  • round — Rounds a number to a given number of digits.
  • floor — Rounds a number down to the nearest integer.

Related recipes

In the tutorial

  • Data types — The main PHP data types — strings, numbers, booleans, arrays and null.

Thanks for reading!

Donate to the site — we work hard for you.