Debutant php PHP 15 min de lecture

Contextes numériques

Contextes Numériques

Comprendre les Contextes Numériques dans PHP

PHP est un langage flexible, et il doit parfois faire des hypothèses sur les types de données avec lesquels il travaille, surtout lors de l'exécution d'opérations mathématiques. Cette conversion automatique des types de données est appelée "jeu de types", et elle est particulièrement pertinente lors de la manipulation de nombres. Lorsque vous utilisez des opérateurs arithmétiques comme +, -, * ou /, PHP tentera de convertir les valeurs impliquées en entiers ou en nombres à virgule flottante pour rendre le calcul possible. Ceci est particulièrement courant lorsque des chaînes de caractères sont impliquées.

Comment PHP Décide : Entier ou Flottant ?

La question cruciale est : comment PHP détermine-t-il si l'opération sera un calcul entier ou à virgule flottante ? La réponse réside dans les types de données des opérandes.

  • Implication des Flottants : Si l'une quelconque des valeurs qui sont additionnées, soustraites, multipliées ou divisées est un flottant, ou si une valeur ne peut pas être convertie de manière fiable en un entier, PHP convertira les deux opérandes en flottants, et le calcul sera effectué en utilisant l'arithmétique à virgule flottante.

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)

Ici, "9,99 dollars" est traité comme une chaîne numérique de tête. PHP extrait "9,99", le convertit en float et effectue l'addition. Encore une fois, un avertissement est généré, mais le calcul est effectué et le résultat est un float.

Conclusion

Comprendre comment PHP gère les contextes numériques, notamment lorsque des chaînes de caractères sont impliquées, est essentiel pour écrire un code précis et prévisible. En connaissant la manière dont PHP effectue les conversions de type implicites et comment il interprète les chaînes numériques de tête, vous pouvez éviter les résultats inattendus et vous assurer que vos calculs sont effectués comme prévu.