My code
<?php
var_dump('0xD' * 1 );
var_dump((int)'0xD');
var_dump(intval('0xD'));
var_dump((float)'0xD');
Actual result:
int(13)
int(0)
int(0)
float(0)
Why result of first two conditions are not same? Can you provide me correct documentation?
All that I found is
- Type Casting: Type casting in PHP works much as it does in C: the name of the desired type is written in parentheses before the variable which is to be cast. It may not be obvious exactly what will happen when casting between certain types. For more information, see these sections:…
- Converting to integer: From strings:
See String conversion to numbers - String conversion to numbers When a string is evaluated in a numeric context, the resulting value and type are determined as follows.
So, As far as I understand, docs say that casting to int directly and by putting in numeric context should be same. What is my mistake?
ADDED: Try to check first and second code (and outputs) before answering.
'0xD'is a string. The documentation clearly specifies how a string is "casted" into an integer value (picking the(int) '0xD';example here):The initial porition of the string
'0xD'that is a number is0, hence the it’s(int) 0.Don’t mix this with writing code. If you write that in code it’s not a string, it’s the hexa-decimal representation/notation of an integer number (Demo):
This does not fully answer why the expression
'0xD' * 1results in(int) 13, but explains everything else so far and which two rules of integer value interpretation apply in PHP.I assume that there is a slight difference between casting to integer and integer context in PHP. If the string representing a hexadecimal number it is used in integer/float context:
In this expression, the string
'0xD'will get evaluated as number because of the*operator and the1operand (see Type Juggling). This is not Type Casting, because there is no cast language construct.It looks like that in this expression’s case, the interpretation of the string as an integer is done literally (as specified) but is not the same as when you do a conversion.
One could argue it remains undocumented when conversion applies and when literal interpretation applies. However, using type casting can get you around any such problems (Demo):