Mathematical operation between string and number in php

-2

What is the explanation for these adverse results if in the two operations I am subtracting a string from a number?

The operation below

echo "Você nasceu em ". date('Y') - 20;

Return -20

and the operations below

echo date('Y') . "Você nasceu em " - 20;

echo "2017 Você nasceu em " - 20;

Return 2007

    
asked by anonymous 24.07.2017 / 17:12

1 answer

1

The conversion of string to integer depends on the format of the string, so PHP evaluates the format of the string and if it does not have any numerical value it will be converted to 0 (zero). If you have numeric value in your first position the value will be considered and if the value is not in the first position it will be disregarded. See the example: ideone

$string = (int) 'Muitas casas';

var_dump( $string ); // int(0)

$string2 = (int) '10 casas aproximadamente';

var_dump( $string2 ); // int(10)

$string3 = (int) 'Exatamente 10 casas';

var_dump( $string3 ); // int(0)

See more in Learn PHP

    
24.07.2017 / 18:18