Search code examples
phpoperatorsbitwise-operators

Bitwise OR operator in PHP, Bug or Feature?


echo 'https://www.tehplayground.com/' | '/';

Results in 'ottps://www.tehplayground.com/'

Why?


Solution

  • That's due to the bitwise OR operator. It interprets each string as binary and performs the operation.

    01101000 // 'h'
    00101111 // '/'
    -- OR --
    01101111 // 'o'
    

    ^ looking at the first character

    Further Explanation

    PHP seems to loop through each character of a string and apply the bitwise operator to it.

    So what actually happens is more like:

    "h" | "/" -> "o"
    "t" | "" -> "t"
    "t" | "" -> "t"
    "p" | "" -> "p"
    ...
    

    Any empty string in bitwise operations would end up being all 0s in binary, so if we just look at the first two characters for comparison

    // character at index [0]
    "h" -> 01101000 (104)
    "/" -> 00101111 (47)
    -- OR --
    "o" -> 01101111 (111)
    
    // character at index [1]
    "t" -> 01110100 (116)
    ""  -> 00000000 (0)
    -- OR --
    "t" -> 01110100 (116)