Mathematical operation between string and number in php

Asked

Viewed 151 times

-2

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

The operation below

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

Returns -20

and the operations below

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

echo "2017 Você nasceu em " - 20;

Returns 2007

  • This was not explained in the other question?

  • @Andersoncarloswoss No, pay attention to the results above, are different

  • 1
  • @rray, good, this I had not seen in the research, Thanks

  • 1

    And that was also explained in question that generated doubt. Isac commented on this cast of string for int in his answer.

  • @Andersoncarloswoss Negative, no one said clearly in this way "The PHP interpretation mechanism works as follows, if the first part of the string is a valid number it is converted(int or float) and the rest is dropped, ...." as rray indicated

  • @Andersoncarloswoss, we are not responding to people with a high degree of knowledge and especially to the language employed, for example, string cast, many will fly to hear this.

  • 1

    And as usual, I downvoto in my question. This adds a lot to the site. Because they did not deny the other https://answall.com/questions/223634/por-que-uso-do-par%C3%Aantesis-affects-a-express%C3%A3o-matem%C3%A1tica-combi-com-uma-con also since there is a response in https://answall.com/questions/80767/por--that-no-php-a-express%C3%A3o-2-6-ma%C3%A7%C3%A3s-%C3%A9-equals-a-8

  • The other question focuses on the problem of using, or not using, parentheses, so the answer would be focused more on the operators' precedence. Your question is already more in the analysis that PHP does in string numerical. I cannot explain the down-vote, but would be duplicate of the question that rray indicated, right?

  • See I said the focus of the answer was the precedence of the operators, it does not mean that it was exclusively that.

  • 1

    correct, but I would not be obliged to read the answers since it was not the same focus and my research did not return the indicated by rray. Type in the search box "Mathematical operation between string and number in php" and see the return!

Show 6 more comments

1 answer

1


The conversion from string to integer depends on the format of the string, so PHP evaluates the format of the string and if it has no numerical value it will be converted to 0(zero). If you have a numerical value in your first position the value will be considered and if the value is not in the first position 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

Browser other questions tagged

You are not signed in. Login or sign up in order to post.