Search code examples
phpdynamic-typingweak-typing

A string in PHP that doesn't make sense


I was experimenting with weak/dynamic typing properties of PHP in preparation for a test and was completely baffled by the output of this string concatenation. Can someone explain how this is even possible?

<?php echo  1 . "/n" . '1' + 1 ?><br />

output:

2


Solution

  • Analysis:

    echo  1 . "/n" . '1' + 1;
    

    is equivalent to

    //joined first 3 items as string
    echo "1/n1"+1;
    

    is equivalent to

    //php faces '+' operator, it parses '1/n1' as number
    //it stops parsing at '/n' because a number doesn't
    //contain this character
    echo "1"+1;
    

    is equivalent to

    echo 1+1;