The problem of exchanging two integer variables (without using the third) is one of the classic programmer riddles.

How to do this in PHP using the minimum number of characters?

Victory criteria - the minimum number of characters. All other things being equal, the answer published earlier wins. Summing up after 24 hours.


Please indicate in the response the number of characters, so that it is easier to identify the winner.

function getAnswers(questionId, answer_filter, page) { return jQuery.ajax({ url: '//api.stackexchange.com/2.2/questions/' + questionId + '/answers?page=' + page + '&pagesize=100&order=desc&sort=activity&site=ru.stackoverflow&filter=' + answer_filter, method: "get", dataType: "jsonp", crossDomain: true }).then(function(data) { if (data.has_more) { return getAnswers(questionId, answer_filter, page + 1).then(function(d) { return data.items.concat(d.items); }) } return data.items; }); } function getAuthorName(e) { return e.owner.display_name } function process(items) { return items.map(function(item) { var matched = item.body.match(/(\d+)[^\d]*?<\/h/); if (matched) { return { count: +matched[1], link: item.share_link, author: getAuthorName(item) }; } else { return { count: 'N/A', link: item.share_link, author: getAuthorName(item) } } }); } function sort(items) { return items.sort(function(a, b) { if (a.count == 'N/A') return 1; if (b.count == 'N/A') return -1; return a.count - b.count; }) } function fillTemplate(sortedItems) { $('#leadership').append(sortedItems.map(function(item, index) { return $('<tr>').append($('<td>').html(index + 1)) .append($('<td>').html(item.author)) .append($('<td>').html(item.count)) .append($('<td>').append($('<a>').attr('href', item.link).text('Link'))); })); return sortedItems; } var QUESTION_ID = 540286, ANSWER_FILTER = "!4*SyY(4Kifo3Mz*lT", startPage = 1; getAnswers(QUESTION_ID, ANSWER_FILTER, startPage) .then(process) .then(sort) .then(fillTemplate); 
 #leadership { border-collapse: collapse; } #leadership td, #leadership th { padding: 5px; } #leadership th, td:nth-child(3) { text-align: center; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <h1>Таблица лидеров</h1> <table id="leadership"> <tr> <th></th> <th>Автор</th> <th>Количество символов</th> <th></th> </tr> </table> 


Comment on the reason for choosing the winner:

The leading answer @PashaPash (0 characters) does not actually change the variables, so it does not participate in the competition.

The answer from @Naumov (10 characters), instead of exchanging variables, simply assigns them new values. Well, its length is not constant, but depends on the values ​​of variables. I will not consider this answer as part of the competition program.

  • Why php? :( - Qwertiy
  • 3
    @Qwertiy, because it's time to develop a community in this direction. And now PHP = кака-код . It's time to change this by asking good, interesting questions. Golf is one of the ways. - Dmitriy Simushev
  • Ahhhh! Sorting leaderboard lost! - VladD
  • one
    @VladD, corrected :) - Grundy
  • 3
    @AK, I have nothing against quality questions on real problems. I just wanted to somehow dilute the boring and monotonous questions about PHP - Dmitriy Simushev

11 answers 11

PHP, 14 characters

 $a+=+$b-$b=$a; 

Working example on IDEOne.

  • 2
    It is curious that the expression $a+=$b-$b=$a; - does not work - Dmitriy Simushev
  • one
    @Sergiks, works steadily everywhere, starting with PHP@4.3.0. Proof (before launching, it is necessary to poke a tick " eol versions ") - Dmitriy Simushev
  • 2
    Somehow it was awkward: the organizer wins the competition) - Sergiks
  • one
    The trick, as I understand it, is in the timing of the calculation of the minus arguments. A unary plus, forming an expression, seems to be the first to resolve to a value. And, apparently, this value is put in an implicit variable. And since the minus gets its arguments by reference, it does not work without a plus. Aaargh - D-side
  • one
    And this is because they have fundamentally different left arguments and grouping by expressions occurs under unequal conditions. Y - left argument can be any expression, and y = exclusively lvalue . Therefore = left of the minus will be executed later (since there may be an expression to the right of it, with operators, with which it can compete for priority), and to the right - earlier (since there lvalue must be directly next to, point-blank). - D-side

PHP, 15 characters

 $x^=$y^=$x^=$y; 
  • What the....??? =) - Dmitriy Simushev
  • one
    @DmitriySimushev, cool right? :-D - Grundy
  • Highly. I would not have thought of it - Dmitriy Simushev
  • Cool. I only always had a list in my head - korytoff
  • 2
    a well-known technique) it has only one minus in C ++ - if x and y are references to the same variable. - pavel

PHP 25 20

 list($a,$b)=[$b,$a]; 
  • Arrays have a short syntax =) - Dmitriy Simushev
  • @DmitriySimushev, is it [] ? - Grundy
  • same competition;) - Dmitriy Simushev
  • @DmitriySimushev, while no one else has joined :-D - Grundy
  • It looks like the competition is too simple - Dmitriy Simushev

PHP, 15 characters

 $a=$a+$b-$b=$a; 
  • @Sergiks, strange, works for me: ideone.com/OFStDr - Dmitriy Simushev
  • one
    My yawn, incorrectly checked. It really works . But the priority of operators after all puts + and earlier = ! Why does this work? :) - Sergiks
  • one
    @Sergiks, this is really interesting. It says here that y = really a lower priority, but the remark gives an example, it is disproving. - Dmitriy Simushev
  • one
    @Sergiks, the list doesn’t have to be - Dmitriy Simushev
  • one
    @DmitriySimushev list() is not an arithmetic operator) I’m talking about your decision, mine with multiplication and division, and Alexei Shimansky. - Sergiks 10:08 pm

17, 19, 23 and 42 characters

 $x=[$y,$y=$x][0]; // 17 $x/=$y=($x*=$y)/$y; // 19 eval("\$x=$y;\$y=$x;"); // 23 extract(unpack("iy/ix",pack("i2",$x,$y))); // 42 
  • The characters' can not be used as integer value - Naumov
  • @Naumov has also realized and removed) - Sergiks
  • 2
    The last method offset - Naumov
  • @Naumov is the magic of the number 42 :) - Sergiks

Quite an alternative:

Reassigning values ​​to variables is generally a bad idea.

  • In terms of readability of the code - looking at the first assignment of values ​​to variables it is hard to understand what they are equal at the end of the method. Especially important for languages ​​with non-strict typing.
  • In terms of performance, it is much more convenient for a processor to simply start taking a value from another place than to waste time on transferring values ​​from one piece of memory to another, and back.

It is much better to simply replace the use of variables in the code that is located below the place where you were going to enter the swap.

PHP, 0 characters

  • In my opinion a very controversial statement. Imagine that for some reason we need, that a was less than b otherwise - swap places. Then according to you, we need to write 2 branches of code under if/else instead of sharing? - pavel
  • 2
    @pavel is not, of course. We must choose a minimum and a maximum and continue to work with this pair. - Pavel Mayorov
  • And if, roughly speaking, I have three foreach cycles in a row to output the result from the database to the template, in the form of tables, but I specifically use some $nomer_po_porjadku variable to designate the number in order in them in the first column ...... then for three tables and cycles, it is all the same to start three different variables, and not to reset the first one and reuse it? - Alexey Shimansky
  • one
    @Alexey Shimansky: In C ++, local variables inside the cycle are not visible from the outside. Well, yes, reusing variables is a bad idea, because it creates unnecessary dependencies between parts of the code. Believe me, the compiler is able to reuse memory areas for unnecessary variables much better. - VladD
  • @VladD локальные переменные внутри цикла таки не видны снаружи ... either I didn’t understand, or)) .. I’m talking about $nomerPp = 1; foreach($something as $item) { doSmth; echo '<div>номер: '.$nomerPp.'</div>'; $nomerPp++; } $nomerPp = 1; foreach($anotherData as $item) { echo '<div>номер: '.$nomerPp.'</div>'; $nomerPp++; } $nomerPp = 1; foreach($thirdArrayOfData as $item) { doSmth; echo '<div>номер: '.$nomerPp.'</div>'; $nomerPp++; } $nomerPp = 1; foreach($something as $item) { doSmth; echo '<div>номер: '.$nomerPp.'</div>'; $nomerPp++; } $nomerPp = 1; foreach($anotherData as $item) { echo '<div>номер: '.$nomerPp.'</div>'; $nomerPp++; } $nomerPp = 1; foreach($thirdArrayOfData as $item) { doSmth; echo '<div>номер: '.$nomerPp.'</div>'; $nomerPp++; } $nomerPp = 1; foreach($something as $item) { doSmth; echo '<div>номер: '.$nomerPp.'</div>'; $nomerPp++; } $nomerPp = 1; foreach($anotherData as $item) { echo '<div>номер: '.$nomerPp.'</div>'; $nomerPp++; } $nomerPp = 1; foreach($thirdArrayOfData as $item) { doSmth; echo '<div>номер: '.$nomerPp.'</div>'; $nomerPp++; } - Alexey Shimanskyj

PHP, 17 characters

 $a=$a+$b-($b=$a); 
  • A little bit doge - Dmitriy Simushev
  • At first I wanted to edit, but I realized that it wasn’t sports =) - Dmitriy Simushev

28 characters for originality in general

 extract(['b'=>$a,'a'=>$b]); 
  • 3
    I did not understand something. You so ardently promoted array() instead of [] , and now you yourself are breaking your principles. Вы учите человека объявлять массивы как [] вместо array(), а потом будете учить <? ?> вместо <?php ?> и т.д Вы учите человека объявлять массивы как [] вместо array(), а потом будете учить <? ?> вместо <?php ?> и т.д ....... ru.stackoverflow.com/questions/511800/… ...... shame on you! - Alexey Shimansky
  • @ Alexey Shimansky You are offended and now you have found one конкурсный answer. I emphasize соревнование,конкурс . And try to control me by this: D Then you got a downvote from me for two obvious reasons: the variable is $array and [] , two factors can lead to an error in the code. And surprisingly, you replaced array() with [] stackoverflow.com/questions/14113256/… ... - Naumov
  • I did not use $array - once ...... I replaced array () with [] - because I follow innovations, and I do not spit saliva from it as an old grumble, and the meaning will not change ..... but that a competitive question or not - does not matter, the main thing is that you do not follow the very rules and standards with which you tried or tried to feed the rest .... and here ru.stackoverflow.com/questions/540542/… generally a hybrid ... yourself undecided .... it's just fu. abomination and dirty trick. - Alexey Shimansky
  • @ AlekseyShimansky The difference is that: With спортивном программирование code does not live a long time, and only you are working on it. stackoverflow.com/questions/14113256/… see in foreach namely foreach($array as $val) { . - Naumov
  • This is called "pereobulsya" and "no clear position." If you think that the world has appeared as a result of a big bang, then entering the building with believers you should not abruptly become a creationist. If you go to the VAZ 2106 alone, then to go with friends somewhere it will not become MERSEDES SLS 500 ..A here ru.stackoverflow.com/questions/540542 you have a germrodrodit. And there is no need to sculpt any other funny words ..... and yes - if you cannot distinguish the $array variable from the array() declaration, then this is again your personal internal problem. Exactly like the perception of the square brackets in the ad - Alexey Shimansky

For fun, 76 characters

 try{ throw new Exception($b); }catch(Exception $e){ $b=$a; $a=$e->getMessage(); } 
  • 2
    By the way, is the use of $ e considered a violation of the conditions of the problem? - rjhdby
  • Considered a violation, yes. You explicitly start a new variable to store the exception. - Dmitriy Simushev
  • @DmitriySimushev here the question is somewhat different. In the case of try / catch, I have no choice whether to declare a variable in catch or not, in fact, this is a language construct. The philosophical question in general. :) - rjhdby
  • An assignment operator is also a construction of a language with which you have no choice whether to declare a variable or not. How exactly to create a variable is not important. The main thing is that there are three of them. - Dmitriy Simushev

PHP 7.1 (16 characters)

 <?php [$a,$b]=[$b,$a]; 
  • one
    A good option. But still too long (16 characters) :) - Dmitriy Simushev
  • one
    But it works not only with numbers) - vp_arth

PHP 10 characters

let's say we have $a=1;$b=5;

to swap them we can do so

$a=5;$b=1;

  • Well, this is not serious and not sports. Imagine me testing your code with such initial conditions: $a=rand(10000, 99999);$b=rand(10000, 99999); . Does the method work? - Dmitriy Simushev
  • @DmitriySimushev in the condition there is no condition that you can not change their hands. This is savvy! And the answer is more comic. Yes, and about the methods of testing or anything in the conditions there. - Naumov
  • 3
    @DmitriySimushev Sense of humor, and unconventional thinking, is a good example to others. I think so: D - Naumov
  • 3
    Well, you almost came up with the perfect solution! If the values ​​are equal, then generally do not do anything. - D-side
  • 6
    Here you are laughing, and in IOCCC in 1994, an empty program participated, as stated "outputting its source code." - D-side