Principiante php PHP 15 min de lectura

Contextos Numéricos

Contextos Numéricos

Comprender los Contextos Numéricos en PHP

PHP es un lenguaje flexible, y a veces necesita hacer suposiciones sobre los tipos de datos con los que está trabajando, especialmente al realizar operaciones matemáticas. Esta conversión automática de tipos de datos se conoce como "manipulación de tipos", y es particularmente relevante al tratar con números. Cuando utiliza operadores aritméticos como +, -, * o /, PHP intentará convertir los valores involucrados en enteros o números de punto flotante para hacer posible el cálculo. Esto es especialmente común cuando se involucran cadenas de texto.

Cómo Decide PHP: Entero o Flotante?

La pregunta crucial es: ¿cómo determina PHP si la operación será un cálculo de entero o de punto flotante? La respuesta reside en los tipos de datos de los operandos.

  • Involucramiento de Flotantes: Si cualquiera de los valores que se están sumando, restando, multiplicando o dividiendo es un flotante, o si un valor no puede convertirse de manera confiable a un entero, PHP convertirá ambos operandos a flotantes, y el cálculo se realizará utilizando aritmética de punto flotante.

Strings and Whitespace

A handy feature is that leading and trailing whitespace in numeric strings is automatically ignored during type juggling. This means you don’t need to worry about cleaning up strings before using them in calculations.

var_dump($answer); // Output: int(2)


The spaces before and after the "1" in the string don't affect the outcome; PHP effectively treats the string as the integer 1.

### Understanding Numeric Contexts in PHP

When performing mathematical operations in PHP, the data types of the values involved—whether they are integers, floating-point numbers, or strings—play a crucial role in determining the outcome and the data type of the result. PHP's behavior in these situations is governed by what's called "numeric context."

### Implicit Type Conversion and Floating-Point Arithmetic

PHP often automatically converts data types to facilitate calculations.  If an arithmetic operation involves an integer and a string that can be interpreted as a number (either an integer or a floating-point number), PHP will convert both operands into floating-point numbers before performing the calculation. This ensures accuracy when dealing with decimal values.

For example:

var_dump($answer);


This code will output:

float(10.9)


Essentially, PHP prioritizes performing floating-point arithmetic when necessary to produce a meaningful numerical result. Otherwise, it will use integer arithmetic.

### Distinguishing Numeric and Leading Numeric Strings

PHP differentiates between two types of strings when it comes to numeric conversions:

- **Numeric Strings:** These are strings that represent a valid number, either an integer or a float, when interpreted as a number.

- **Leading Numeric Strings:** These strings begin with a numeric portion but also contain non-numeric characters (like letters, symbols, or spaces).

The key difference lies in how PHP handles these strings during type conversions. When a leading numeric string is used in an arithmetic expression, PHP extracts the initial numeric portion.  Any characters following the first non-numeric character are discarded. If a string starts with a non-numeric character, PHP considers the entire string as non-numeric and cannot convert it to a number.

**Important Exception:**  PHP ignores leading or trailing spaces when determining if a string is numeric. A string that begins with spaces followed by numeric characters will be treated as a numeric string.

### Examples of Leading Numeric String Behavior

Let's illustrate this with examples:

Consider this code:

var_dump($answer);


The output will be:

int(2)


Even though the string "1 dollar" contains non-numeric characters, PHP extracts the "1" at the beginning, converts it to an integer, and performs the addition.  You're likely to see a warning message indicating that a non-numeric value was encountered. However, the operation proceeds because both operands can be interpreted as integers.

Similarly, with a floating-point number embedded in a leading numeric string:

var_dump($answer);


This will produce:

int(10.99)

Aquí, "9.99 dólares" se trata como una cadena numérica inicial. PHP extrae "9.99", lo convierte a un float y realiza la adición. De nuevo, se genera una advertencia, pero el cálculo se ejecuta y el resultado es un float.

Conclusión

Comprender cómo PHP maneja los contextos numéricos, especialmente cuando se involucran cadenas de texto, es crucial para escribir código preciso y predecible. Al saber cómo PHP realiza conversiones de tipo implícitas y cómo interpreta las cadenas numéricas iniciales, puede evitar resultados inesperados y asegurarse de que sus cálculos se realicen como se pretende.