0
  1. this is code:

        <?php
        $a = "4 fox and 3 cows"; // it is simple string
        $b = 22;
        echo $ab = $a + $b;
        echo "output::".$ab;
        ?>'
    

    output: only first index is being read 26 what is the logic behind this..? instead I should get an error..

2.another example:

     <?php
        $a = "four fox and 3 cows"; // it is simple string
        $b = 22;
        echo $ab = $a + $b;
        echo "output::".$ab;
        ?>'
   output:
   22
   what is the logic behind this..?

4 Answers4

4

You should look into Type Juggling, php does it's best to accommodate the ability to transform type casting on the fly, using the + operator in php is meant for 2 numbers whether they are integer, decimal, etc.

Since strings don't have an integral value, when you use the + operator it will use the first part of the string that can make up a valid integer.

Since your example starts with "4 " it truncates everything else and turns the 4 into an integer making it 4+22 which is 26.

iam-decoder
  • 2,554
  • 1
  • 13
  • 28
  • 2
    For this to be a good answer you should at least call it by its name: type juggling. It's an important thing to know in PHP. – John Conde Jun 18 '15 at 18:27
0

Use the . operator to concatenate strings.

The + operator will convert the strings to numerics and add them

Alexandre
  • 306
  • 1
  • 7
0

If you wanted to concat the number with the string, the operator in php is ., not +.

otherwise, why would you want to add a number with a string? What result did you expect? It seems in these case php parses the string to int, ignoring everything that comes after the number it can understand.

pablito.aven
  • 1,135
  • 1
  • 11
  • 29
0

+ just converts your string to int, stripping everything unknown to a number.

"4 fox and 3 cows"

^^> everything there gets stripped, because a number can't be processed of fox and 3 cows, php reads the number from left to right and once it meets something weird, it stops.

nicael
  • 18,550
  • 13
  • 57
  • 90