How to exchange values of two variables without using a third one in php

0

My question is very objective. I need to swap values of two variables without using a third one in php. Using vector / array is not an option.

Searching found a solution in linguagem c here , but I could not get through php . I've also found this solution , however a peculiar bug is happening.

This is my code:

        $change_provider = "Desenvolvimento Web";
        $change_receiver = "SEO(Search Engine Optimization)";

        $change_provider ^= $change_receiver ^= $change_provider ^= $change_receiver;

        print_r($change_provider); //string(19) "SEO(Search Engine O" 
        print_r($change_receiver); //string(19) "Desenvolvimento Web"

Notice that my output is missing some characters at the end. How to solve this problem? Thanks for helping.

    
asked by anonymous 03.08.2016 / 19:42

2 answers

4

Basically this:

list( $a, $b ) = array( $b, $a );

In newer versions:

list( $a, $b ) = [ $b, $a ];


It is important to note that both the above solutions and the use of a third variable are effective in that they do not depend on memory reallocation, since there is only an exchange of references, not values. >

It skips a bit from the question, but just to note, note that the PHP references are at a level higher than the C pointers, which are memory locations. Regardless of that, the exchange of position is inexpensive in both languages.


Your solution, the XOR Swap is just for numbers:

$change_provider ^= $change_receiver ^= $change_provider ^= $change_receiver;

It is based on a mathematical property of XOR:

  

How does the Xor Swap algorithm work?


As you already noticed in your test, it works with strings, but just because they are treated as a sequence of bytes, see mention in @Omine's answer

    
03.08.2016 / 20:12
2

Given the conditions, the most appropriate form would be using XOR Swap algorithm. That is, the same as you presented in the question using bitwise operators.

However, to function as desired, within the context of the question, you need both variables to have the same amount of bytes . That is, you can use strings, not just numeric values. What matters is the amount of bytes.

note: The test you submitted in the question does not return a bug. The variable with a larger string is cut off because it is larger than the other variable.

    
03.08.2016 / 20:02