Home > Software design >  Precedence of cast operators in php
Precedence of cast operators in php

Time:09-15

Precedence isn't very well explained in php see here: https://www.php.net/manual/en/language.operators.precedence.php

this isn't clear for example:

$x = (float)'100'/100;

will this first cast '100' to float, then make the division, or divide first, then make the cast?

CodePudding user response:

As your link https://www.php.net/manual/en/language.operators.precedence.php already explains, the table is ordered by precedence.

First, you've got in line 3 the type cast (https://www.php.net/manual/en/language.types.type-juggling.php#language.types.typecasting), than the 6th line (arithmetic operators).

Your code is equivalent to

$x = ((float)'100') / 100;

or

$y = (float)'100';
$x = $y / 100;

respectively.

CodePudding user response:

According to the table you linked to, type casting has higher precedence (row 3) than multiplication and division operators (row 6). So it's treated as

$x = ((float)'100') / 100;

It first casts '100' to float, then performs the division.

  •  Tags:  
  • php
  • Related