Sie sind auf Seite 1von 16

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

Downloads
Documentation
Get Involved
Help

Search
PHPKonf: Istanbul PHP Conference 2017
Getting Started
Introduction
A simple tutorial
Language Reference
Basic syntax
Types
Variables
Constants
Expressions
Operators
Control Structures
Functions
Classes and Objects
Namespaces
Errors
Exceptions
Generators
References Explained
Predefined Variables
Predefined Exceptions
Predefined Interfaces and Classes
Context options and parameters
Supported Protocols and Wrappers
Security
Introduction
General considerations
Installed as CGI binary
Installed as an Apache module
Session Security
Filesystem Security
Database Security
Error Reporting
Using Register Globals
User Submitted Data
Magic Quotes
Hiding PHP
Keeping Current
1 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

Features
HTTP authentication with PHP
Cookies
Sessions
Dealing with XForms
Handling file uploads
Using remote files
Connection handling
Persistent Database Connections
Safe Mode
Command line usage
Garbage Collection
DTrace Dynamic Tracing
Function Reference
Affecting PHP's Behaviour
Audio Formats Manipulation
Authentication Services
Command Line Specific Extensions
Compression and Archive Extensions
Credit Card Processing
Cryptography Extensions
Database Extensions
Date and Time Related Extensions
File System Related Extensions
Human Language and Character Encoding Support
Image Processing and Generation
Mail Related Extensions
Mathematical Extensions
Non-Text MIME Output
Process Control Extensions
Other Basic Extensions
Other Services
Search Engine Extensions
Server Specific Extensions
Session Extensions
Text Processing
Variable and Type Related Extensions
Web Services
Windows Only Extensions
XML Manipulation
GUI Extensions
Keyboard Shortcuts
?
This help
j
Next menu item
k
Previous menu item
gp
2 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

Previous man page


gn
Next man page
G
Scroll to bottom
gg
Scroll to top
gh
Goto homepage
gs
Goto search
(current page)
/
Focus search box
Nmeros de punto flotante
Booleanos
Manual de PHP
Referencia del lenguaje
Tipos
Change language:

Spanish

Edit Report a Bug

Nmeros enteros (Integers)


Un nmero entero (o integer) es un nmero del conjunto = {..., -2, -1, 0, 1,
2, ...}.
Vase tambin:
Enteros de longitud arbitraria / GMP
Nmeros de punto flotante
Precisin arbitraria / BCMath

Sintaxis
Los integer pueden especificarse mediante notacin decimal (base 10),
hexadecimal (base 16), octal (base 8) o binaria (base 2), opcionalmente
precedidos por un signo (- o +).
Los literales de tipo integer binarios estn disponibles desde PHP 5.4.0.
Para utilizar la notacin octal, se antepone al nmero un 0 (cero). Para
utilizar la notacin hexadecimal, se antepone al nmero 0x. Para utilizar la
notacin binaria, se antepone al nmero 0b.

3 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

Ejemplo #1 Literales de nmeros enteros


<?php
$a=1234;//nmerodecimal
$a=-123;//unnmeronegativo
$a=0123;//nmerooctal(equivalea83decimal)
$a=0x1A;//nmerohexadecimal(equivalea26decimal)
$a=0b11111111;//nmerobinario(equivaleal255decimal)
?>

Formalmente, la estructura de los literales de tipo integer es:


decimal

: [1-9][0-9]*
| 0

hexadecimal : 0[xX][0-9a-fA-F]+
octal

: 0[0-7]+

binario

: 0b[01]+

entero

:
|
|
|

[+-]?decimal
[+-]?hexadecimal
[+-]?octal
[+-]?binario

El tamao de un integer depende de la plataforma, aunque el valor usual es


un valor mximo de aproximadamente dos mil millones (esto es, 32 bits con
signo). Las plataformas de 64 bits normalmente tienen un valor mximo de
aproximadamente 9E18, excepto en Windows antes de PHP 7, que siempre
es de 32 bits. PHP no tiene soporte para el tipo integer sin signo. El tamao
de un integer se puede determinar mediante la constante PHP_INT_SIZE, y el
valor mximo mediante la constante PHP_INT_MAX desde PHP 4.4.0 y PHP 5.0.5,
y el valor mnimo mediante la constante PHP_INT_MIN desde PHP 7.0.0.
Advertencia
Antes de PHP 7, si a un integer octal se le proporcionaba un dgito no vlido
(esto es, 8 o 9), se ignoraba el resto del nmero. Desde PHP 7, se emite un
error de anlisis.

Desbordamiento de enteros
Si PHP encuentra un nmero fuera de los lmites de un integer, se
interpretar en su lugar como un valor de tipo float. Tambin, una operacin
cuyo resultado sea un nmero fuera de los lmites de un integer devolver en
su lugar un valor de tipo float.
Ejemplo #2 Desbordamiento de enteros en sistemas de 32 bit
<?php
$nmero_grande=2147483647;
var_dump($nmero_grande);//int(2147483647)

4 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

$nmero_grande=2147483648;
var_dump($nmero_grande);//float(2147483648)
$milln=1000000;
$nmero_grande=50000*$milln;
var_dump($nmero_grande);//float(50000000000)
?>

Ejemplo #3 Desbordamiento de enteros en sistemas de 64 bit


<?php
$nmero_grande=9223372036854775807;
var_dump($nmero_grande);//int(9223372036854775807)
$nmero_grande=9223372036854775808;
var_dump($nmero_grande);//float(9.2233720368548E+18)
$milln=1000000;
$nmero_grande=50000000000000*$milln;
var_dump($nmero_grande);//float(5.0E+19)
?>

No existe el operador de divisin de integer en PHP. 1/2 produce el float 0.5.


El valor puede ser convertido a un integer redondendolo a cero, o mediante
la funcin round() que permite un mayor control sobre el redondeo.
<?php
var_dump(25/7);//float(3.5714285714286)
var_dump((int)(25/7));//int(3)
var_dump(round(25/7));//float(4)
?>

Conversin a nmeros enteros


Para convertir explcitamente un valor al tipo integer se puede emplear tanto
(int) como (integer). Sin embargo, la mayora de las veces la conversin no es
necesaria, ya que un valor es convertido de forma automtica cuando un
operador, funcin o estructura de control requiera un argumento de tipo
integer. Un valor tambin puede ser convertido al tipo integer mediante la
funcin intval().
Si un resource es convertido a un integer, el resultado ser el nmero de
recurso nico asignado al resource por PHP durante la ejecucin.
Consulte tambin la Manipulacin de tipos.
Desde booleanos
FALSE

5 de 16

producir 0 (cero), y

TRUE

producir 1 (uno).

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

Desde nmeros de punto flotante


Cuando se convierte un float a un integer, el nmero ser redondeado hacia
cero.
Si el valor de tipo float esta por debajo de los lmites de un integer
(normalmente +/- 2.15e+9 = 2^31 en plataformas de 32 bits y +/- 9.22e+18
= 2^63 en plataformas de 64 bits distintas de Windows), el resultado es
indefinido, debido a que float no tiene la precisin suficiente para ofrecer el
resultado como un integer exacto. No se mostrar ninguna advertencia, ni
siquiera un aviso, cuando esto ocurra.
Nota:
A partir de PHP 7.0.0,0, en lugar de ser indefinidos y dependientes
de la plataforma, NaN e Infinity siempre sern cero al amoldarlos a
integer.
Advertencia
Nunca se debe convertir una fraccin desconocida a un integer, ya que a
veces puede conducir a resultados inesperados.
<?php
echo(int)((0.1+0.7)*10);//muestra7!
?>

Consulte tambin la advertencia sobre la precisin de float


Desde cadenas de caracteres
Consulte Conversin de string a nmeros
Desde otros tipos
Precaucin
El comportamiento de la conversin de integer a otros tipos es indefinido. No
confe en ningn comportamiento observado, ya que puede cambiar sin
previo aviso.
add a note

User Contributed Notes 20 notes


up
down
38
d_n at NOSPAM dot Loryx dot com
9 years ago
Here are some tricks to convert from a "dotted" IP address to a LONG int, and

6 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

backwards. This is very useful because accessing an IP addy in a database table is very
much faster if it's stored as a BIGINT rather than in characters.
IP to BIGINT:
<?php
$ipArr = explode('.',$_SERVER['REMOTE_ADDR']);
$ip = $ipArr[0] * 0x1000000
+ $ipArr[1] * 0x10000
+ $ipArr[2] * 0x100
+ $ipArr[3]
;
?>
IP as BIGINT read from db back to dotted form:
Keep in mind, PHP integer operators are INTEGER -- not long. Also, since there is no
integer divide in PHP, we save a couple of S-L-O-W floor (<division>)'s by doing
bitshifts. We must use floor(/) for $ipArr[0] because though $ipVal is stored as a long
value, $ipVal >> 24 will operate on a truncated, integer value of $ipVal! $ipVint is,
however, a nice integer, so
we can enjoy the bitshifts.
<?php
$ipVal = $row['client_IP'];
$ipArr = array(0 =>
floor( $ipVal / 0x1000000) );
$ipVint = $ipVal-($ipArr[0]*0x1000000); // for clarity
$ipArr[1] = ($ipVint & 0xFF0000) >> 16;
$ipArr[2] = ($ipVint & 0xFF00 ) >> 8;
$ipArr[3] = $ipVint & 0xFF;
$ipDotted = implode('.', $ipArr);
?>

up
down
16
Anonymous
2 years ago
Converting to an integer works only if the input begins with a number
(int) "5txt" // will output the integer 5
(int) "before5txt" // will output the integer 0
(int) "53txt" // will output the integer 53
(int) "53txt534text" // will output the integer 53

up
down
22
php at richardneill dot org
3 years ago
A leading zero in a numeric literal means "this is octal". But don't be confused: a
leading zero in a string does not. Thus:
$x = 0123; // 83

7 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

$y = "0123" + 0 // 123

up
down
25
rustamabd@gmail-you-know-what
10 years ago
Be careful with using the modulo operation on big numbers, it will cast a float
argument to an int and may return wrong results. For example:
<?php
$i = 6887129852;
echo "i=$i\n";
echo "i%36=".($i%36)."\n";
echo "alternative i%36=".($i-floor($i/36)*36)."\n";
?>
Will output:
i=6.88713E+009
i%36=-24
alternative i%36=20

up
down
2
litbai
10 months ago
<?php
$ipArr = explode('.', $ipString);
$ipVal = ($ipArr[0] << 24)
+ ($ipArr[1] << 16)
+ ($ipArr[2] << 8)
+ $ipArr[3]
;
?>
1. the priority of bit op is lower than '+',so there should be brackets.
2. there is no unsighed int in PHP, if you use 32 bit versionthe code above will get
negative result when the first position of IP string greater than 127.
3. what the code actually do is calculate the integer value of transformed 32 binary
bit from IP string.

up
down
10
darkshire
9 years ago
d_n at NOSPAM dot Loryx dot com
13-Aug-2007 05:33
Here are some tricks to convert from a "dotted" IP address to a LONG int, and
backwards. This is very useful because accessing an IP addy in a database table is very
much faster if it's stored as a BIGINT rather than in characters.
IP to BIGINT:
<?php
$ipArr = explode('.',$_SERVER['REMOTE_ADDR']);

8 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

$ip = $ipArr[0] * 0x1000000


+ $ipArr[1] * 0x10000
+ $ipArr[2] * 0x100
+ $ipArr[3]
;
?>
This can be written in a bit more efficient way:
<?php
$ipArr = explode('.',$_SERVER['REMOTE_ADDR']);
$ip = $ipArr[0]<<24
+ $ipArr[1]<<16
+ $ipArr[2] <<8
+ $ipArr[3]
;
?>
shift is more cheaper.

up
down
2
Anonymous
9 years ago
To force the correct usage of 32-bit unsigned integer in some functions, just add '+0'
just before processing them.
for example
echo(dechex("2724838310"));
will print '7FFFFFFF'
but it should print 'A269BBA6'
When adding '+0' php will handle the 32bit unsigned integer
correctly
echo(dechex("2724838310"+0));
will print 'A269BBA6'

up
down
0
dewi at dewimorgan dot com
1 year ago
Note that the soft-typing of numbers in PHP means that some things become very
difficult. For example, efficiently emulating the more common linear congruential
generators (LCGs) for fast, deterministic, pseudo-randomness. The naive code to create
the next value in a sequence (for power-of-2 values of $m) is:
$seed = ($seed * $a + $c) % $m;
...where $m, $a, and $c are values and data types carefully chosen such that repeating
this operation will eventually generate every value in the range $0 to $m, with no
repetition.

9 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

I can find no good commonly used LCGs which use PHP-compatible values. The LCG values
used in by rand() in systems like Borland Delphi, Virtual Pascal, MS Visual/Quick
C/C++, VMS's MTH$RANDOM, old versions of glibc, Numerical Recipes, glibc, GCC, ANSI C,
Watcom, Digital Mars, CodeWarrior, IBM VisualAge C/C++, java.util.Random, Newlib,
MMX... *all* fail when ported, for one of two reasons, and sometimes both:
- In PHP on 32 bit machines and all Windows machines, $m = 2^32 or larger requires UInt
or even UInt64, or the result becomes negative.
- Large $a multiplied by an integer seed gets converted to a float64, but the number
can be too long for the 53-bit mantissa, and it drops the least significant digits...
but the LCG code above requires that the most significant digits should be lost.
These are two classes of problem to beware of when porting integer math to PHP, and I
see no clean and efficient way to avoid either one.
So if designing a cross-platform system that must work in PHP, you must select LCG
values that fit the following criteria:
$m = 2^31 or less (PHP limitation). Recommend: 2^31.
$a = Less than 2^22 (PHP limitation); $a-1 divisible by all prime factors of $m; $a-1
divisible by 4 if $m is. Recommend: 1+(4*(any prime <= 1048573)).
$c = smaller than (2^53-($m*$a)) (PHP limitation); relatively prime with $m. Recommend:
any prime <= 23622320123.

up
down
-1
Jacek
9 years ago
On 64 bits machines max integer value is 0x7fffffffffffffff (9 223 372 036 854 775
807).

up
down
-4
pere dot cil at wanadoo dot fr
5 years ago

up
down

10 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

-3
Anonymous
13 years ago

up
down
-5
wbcarts at juno dot com
8 years ago

11 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

up
down
-5
popefelix at gmail dot com
10 years ago

12 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

up
down
-8
eric
8 years ago

13 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

up
down
-8
rickard_cedergren at yahoo dot com
11 years ago

up
down
-9
php at keith tyler dot com
5 years ago

14 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

PHP_INT_MAX (and vice versa for negative numbers).


The Q&D no-muss solution is to cast to (float) instead.

up
down
-11
Hamza Burak Ylmaz
8 years ago

up
down
-16
jmw254 at cornell dot edu
10 years ago

up
down

15 de 16

14/01/17 13:55

PHP: Nmeros enteros (Integers) - Manual

http://php.net/manual/es/language.types.integer.php

-16
sean dot gilbertson at gmail dot com
8 years ago

up
down
-26
Richard
5 years ago

add a note

Tipos
Introduccin
Booleanos
Nmeros enteros (Integers)
Nmeros de punto flotante
Cadenas de caracteres (Strings)
Arrays
Objetos
Recursos
NULO
Llamadas de retorno (Callbacks / Callables)
Seudotipos y variables usadas en esta documentacin
Manipulacin de tipos
Copyright 2001-2017 The PHP Group
My PHP.net
Contact
Other PHP.net sites
Mirror sites
Privacy policy

16 de 16

14/01/17 13:55

Das könnte Ihnen auch gefallen