150
\$\begingroup\$

Your task, if you wish to accept it, is to write a program that outputs a positive integer (higher than 0). The tricky part is that if I duplicate your source code, the output must be double the original integer.

Rules

  • You must build a full program. That is, your output has to be printed to STDOUT.

  • The initial source must be at least 1 byte long.

  • Both the integers must be in base 10 (outputting them in any other base or with scientific notation is forbidden).

  • Your program must not take input (or have an unused, empty input).

  • Outputting the integers with trailing / leading spaces is allowed.

  • You may not assume a newline between copies of your source.

  • This is , so the shortest (original) code in each language wins!

  • Default Loopholes apply.

Example

Let's say your source code is ABC and its corresponding output is 4. If I write ABCABC instead and run it, the output must be 8.

Leaderboard

This uses uses @manatwork's layout.

/* Configuration */

var QUESTION_ID = 132558; // Obtain this from the url
// It will be like https://XYZ.stackexchange.com/questions/QUESTION_ID/... on any question page
var ANSWER_FILTER = "!t)IWYnsLAZle2tQ3KqrVveCRJfxcRLe";
var COMMENT_FILTER = "!)Q2B_A2kjfAiU78X(md6BoYk";
var OVERRIDE_USER = 8349457; // This should be the user ID of the challenge author.

/* App */

var answers = [], answers_hash, answer_ids, answer_page = 1, more_answers = true, comment_page;

function answersUrl(index) {
  return "https://api.stackexchange.com/2.2/questions/" +  QUESTION_ID + "/answers?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + ANSWER_FILTER;
}

function commentUrl(index, answers) {
  return "https://api.stackexchange.com/2.2/answers/" + answers.join(';') + "/comments?page=" + index + "&pagesize=100&order=desc&sort=creation&site=codegolf&filter=" + COMMENT_FILTER;
}

function getAnswers() {
  jQuery.ajax({
    url: answersUrl(answer_page++),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      answers.push.apply(answers, data.items);
      answers_hash = [];
      answer_ids = [];
      data.items.forEach(function(a) {
        a.comments = [];
        var id = +a.share_link.match(/\d+/);
        answer_ids.push(id);
        answers_hash[id] = a;
      });
      if (!data.has_more) more_answers = false;
      comment_page = 1;
      getComments();
    }
  });
}

function getComments() {
  jQuery.ajax({
    url: commentUrl(comment_page++, answer_ids),
    method: "get",
    dataType: "jsonp",
    crossDomain: true,
    success: function (data) {
      data.items.forEach(function(c) {
        if (c.owner.user_id === OVERRIDE_USER)
          answers_hash[c.post_id].comments.push(c);
      });
      if (data.has_more) getComments();
      else if (more_answers) getAnswers();
      else process();
    }
  });  
}

getAnswers();

var SCORE_REG = /<h\d>\s*([^\n,]*[^\s,]),.*?(-?\d+)(?=[^\n\d<>]*(?:<(?:s>[^\n<>]*<\/s>|[^\n<>]+>)[^\n\d<>]*)*<\/h\d>)/;

var OVERRIDE_REG = /^Override\s*header:\s*/i;

function getAuthorName(a) {
  return a.owner.display_name;
}

function process() {
  var valid = [];
  
  answers.forEach(function(a) {
    var body = a.body;
    a.comments.forEach(function(c) {
      if(OVERRIDE_REG.test(c.body))
        body = '<h1>' + c.body.replace(OVERRIDE_REG, '') + '</h1>';
    });
    
    var match = body.match(SCORE_REG);
    if (match)
      valid.push({
        user: getAuthorName(a),
        size: +match[2],
        language: match[1],
        link: a.share_link,
      });
    
  });
  
  valid.sort(function (a, b) {
    var aB = a.size,
        bB = b.size;
    return aB - bB
  });

  var languages = {};
  var place = 1;
  var lastSize = null;
  var lastPlace = 1;
  valid.forEach(function (a) {
    if (a.size != lastSize)
      lastPlace = place;
    lastSize = a.size;
    ++place;
    
    var answer = jQuery("#answer-template").html();
    answer = answer.replace("{{PLACE}}", lastPlace + ".")
                   .replace("{{NAME}}", a.user)
                   .replace("{{LANGUAGE}}", a.language)
                   .replace("{{SIZE}}", a.size)
                   .replace("{{LINK}}", a.link);
    answer = jQuery(answer);
    jQuery("#answers").append(answer);

    var lang = a.language;
    if (! /<a/.test(lang)) lang = '<i>' + lang + '</i>';
    lang = jQuery(lang).text().toLowerCase();

    languages[lang] = languages[lang] || {lang: a.language, user: a.user, size: a.size, link: a.link, uniq: lang};
  });

  var langs = [];
  for (var lang in languages)
    if (languages.hasOwnProperty(lang))
      langs.push(languages[lang]);

  langs.sort(function (a, b) {
    if (a.uniq > b.uniq) return 1;
    if (a.uniq < b.uniq) return -1;
    return 0;
  });

  for (var i = 0; i < langs.length; ++i)
  {
    var language = jQuery("#language-template").html();
    var lang = langs[i];
    language = language.replace("{{LANGUAGE}}", lang.lang)
                       .replace("{{NAME}}", lang.user)
                       .replace("{{SIZE}}", lang.size)
                       .replace("{{LINK}}", lang.link);
    language = jQuery(language);
    jQuery("#languages").append(language);
  }

}
body { text-align: left !important}

#answer-list {
  padding: 10px;
  width: 290px;
  float: left;
}

#language-list {
  padding: 10px;
  width: 290px;
  float: left;
}

table thead {
  font-weight: bold;
}

table td {
  padding: 5px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="//cdn.sstatic.net/Sites/codegolf/all.css?v=617d0685f6f3">
<div id="answer-list">
  <h2>Leaderboard</h2>
  <table class="answer-list">
    <thead>
      <tr><td></td><td>Author</td><td>Language</td><td>Size</td></tr>
    </thead>
    <tbody id="answers">

    </tbody>
  </table>
</div>
<div id="language-list">
  <h2>Winners by Language</h2>
  <table class="language-list">
    <thead>
      <tr><td>Language</td><td>User</td><td>Score</td></tr>
    </thead>
    <tbody id="languages">

    </tbody>
  </table>
</div>
<table style="display: none">
  <tbody id="answer-template">
    <tr><td>{{PLACE}}</td><td>{{NAME}}</td><td>{{LANGUAGE}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr>
  </tbody>
</table>
<table style="display: none">
  <tbody id="language-template">
    <tr><td>{{LANGUAGE}}</td><td>{{NAME}}</td><td><a href="{{LINK}}">{{SIZE}}</a></td></tr>
  </tbody>
</table>

\$\endgroup\$
33
  • 2
    \$\begingroup\$ @Mr.Xcoder Then I'll just have to include one in my own source. \$\endgroup\$
    – steenbergh
    Jul 15, 2017 at 17:55
  • 3
    \$\begingroup\$ @Mr.Xcoder I think that you should have prevented reading your own source code. \$\endgroup\$ Jul 15, 2017 at 18:09
  • 2
    \$\begingroup\$ It only needs to work when doubled once? We don't need to support n many doublings? \$\endgroup\$ Jul 16, 2017 at 8:36
  • 8
    \$\begingroup\$ @Daniel Let's say your source is `` (empty program) and it produces 5. If you double it, your source is `` (empty program) and that produces 5 as well, no matter what you do. That being said, an empty program duplicated is still the empty program, and always produces the same output, except for the case where the empty program means something else (a random number generator, for example), which could not be valid anyway. \$\endgroup\$
    – Mr. Xcoder
    Jul 17, 2017 at 9:11
  • 1
    \$\begingroup\$ This shouldn't be hard for esolangs that automatically dump the top of stack upon program termination. \$\endgroup\$
    – MD XF
    Jul 18, 2017 at 22:26

161 Answers 161

6
\$\begingroup\$

Batch, 13 bytes

@echo %~z0
:

Explanation: %~z0 expands to the length of the source file, so doubling the file simply doubles the length. The second line defines an empty label, which does nothing. When the file is doubled, it becomes a label named @echo %~z0 instead, while the third line is another empty label.

\$\endgroup\$
6
\$\begingroup\$

QBasic,  44  28 bytes

There is no newline at the end. Outputs 4 when single, 8 when doubled.

4
READ x,y
?x+y
END
DATA 4,0

Explanation

For the single version:

  • 4 is a line number.
  • READ x,y takes the first two values from the DATA statement and stores them in x and y. Thus, x gets 4 and y gets 0.
  • ?x+y adds the two numbers and prints them.
  • END exits the program.

In the doubled version, the DATA statement becomes DATA 4,04, which assigns 4 to both x and y, thus making x+y equal 8 instead.

\$\endgroup\$
0
6
\$\begingroup\$

Befunge-98 (PyFunge), 3 bytes

This answer draws heavy inspiration from this one, go vote them up too!

".@

Try it online! or Try it online doubled!

Explanation

When wrapping back around to the beginning of the source in quote mode, this Befunge-98 interpreter pushes at least 1 space (ASCII 32). If we print this value and exit, we get 32.

If we double the source code, we don't wrap back around, but rather end quote mode with the duplicated ". This means that the last character pushed is not a space, but a @, with (drumroll) ASCII 64! A complete coincidence that the character that ends the program in Befunge is twice that of a space.

\$\endgroup\$
6
\$\begingroup\$

Perl 5, 7 bytes

With -M5.10.0

say
+1#

Try it online!

Doubled:

say
+1#say
+1

-2 thanks to Ton Hospel

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Use say to gain 2 more bytes (The -M5.10.0 or -E instead of -e is free) \$\endgroup\$
    – Ton Hospel
    Feb 17, 2018 at 23:19
5
\$\begingroup\$

PHP, 30 bytes

Original

<?=strlen(file(__FILE__)[0]);#

Try it online!

PHP, 60 bytes

doubled

<?=strlen(file(__FILE__)[0]);#<?=strlen(file(__FILE__)[0]);#

Try it online!

\$\endgroup\$
5
  • \$\begingroup\$ Port of the Python solution? \$\endgroup\$
    – Mr. Xcoder
    Jul 15, 2017 at 16:57
  • \$\begingroup\$ @Mr.Xcoder after your comment I have saw the python solution. It is the same way \$\endgroup\$ Jul 15, 2017 at 17:07
  • 1
    \$\begingroup\$ Why not <?=strlen(file(__FILE__)[0]);# \$\endgroup\$
    – Darren H
    Jul 15, 2017 at 17:34
  • \$\begingroup\$ @DarrenH I have not thinking about it \$\endgroup\$ Jul 15, 2017 at 17:45
  • \$\begingroup\$ this is 23 bytes: <?=filesize(__FILE__);# - and doubled is 46 bytes. \$\endgroup\$
    – hanshenrik
    Jul 23, 2017 at 13:27
5
\$\begingroup\$

Hexagony, 4 bytes

[@!)

Try it online! or Try it doubled online!

This solution was found using brute force by Martin and prints 002 regularly and 4 when doubled. This is the only 4 byte solution, but there are several hundred 5 byte solutions.

Expanded versions:

Regular:

 [ @
! ) .
 . .

Doubled:

  [ @ !
 ) [ @ !
) . . . .
 . . . .
  . . .

Hexagony has 6 instruction pointers, one starting at each corner of the hexagon and initially moving "clockwise." The [ instruction causes the interpreter to change IP one left. The first program leads us on a bit of a merry go around, executing: [![.!.)[...)!@ which results in the 002 output. The other program is a bit more tame, executing: [))[..)...[.......)!@ which results in the clean 4.

\$\endgroup\$
5
\$\begingroup\$

Python, 15 bytes

1or exit(2)
0/0

Outputs via exit code. Divides by zero and exits with code 1. Doubled:

1or exit(2)
0/01or exit(2)
0/0

Calls exit(2) and exits with code 2.

Python?, 9 bytes

';exit(2)

Throws a syntax error and exits with code 1. Doubled:

';exit(2)';exit(2)

Calls exit(2) and exits with code 2.

\$\endgroup\$
5
\$\begingroup\$

JavaScript (REPL), 2 bytes

So long as putting code in the console counts as a full program:

+1
\$\endgroup\$
4
  • \$\begingroup\$ Putting the code in the console does not count as a full program. This is a snippet and therefore, unfortunatly, invalid. \$\endgroup\$
    – Pavel
    Jul 17, 2017 at 17:05
  • \$\begingroup\$ Even if I make as REPL? \$\endgroup\$ Jul 18, 2017 at 9:19
  • 3
    \$\begingroup\$ I'd say mark it as REPL and run with it. People who have sour grapes over "JavaScript REPL" but not over the various golfing languages which get such things down to one byte are being oddly specific with their moralistic tendencies. The interpreter which runs JS REPL code is a lot more straightforward than, say, Bubblegum. \$\endgroup\$
    – CR Drost
    Jul 18, 2017 at 21:31
  • \$\begingroup\$ Marked as REPL. \$\endgroup\$ Jul 19, 2017 at 10:36
5
\$\begingroup\$

J, 2 bytes

+1

+1 is 1, and +1+1 is 2.

Fun fact: since J's operator precedence is just right-to-left, this is interpreted as +(1+1)

\$\endgroup\$
4
  • 3
    \$\begingroup\$ This is a real Polyglot: Python REPL, APL, J, Pip \$\endgroup\$
    – Mr. Xcoder
    Jul 15, 2017 at 21:30
  • \$\begingroup\$ @Mr.Xcoder To be fair it works in pretty much every non-esoteric language with a REPL. \$\endgroup\$
    – Cyoce
    Jul 16, 2017 at 22:54
  • 1
    \$\begingroup\$ I thought J's operator precedence was right to left? e.g. 3*6+5 = 33 \$\endgroup\$ Jul 21, 2017 at 18:38
  • \$\begingroup\$ @RichardDonovan right. I goofed \$\endgroup\$
    – Cyoce
    Jul 22, 2017 at 0:37
5
\$\begingroup\$

Whispers v2, 23 bytes

+1
> 1
>> Output 3
>> 1

Try it online! or Try it online doubled

Outputs 1 normally and 2 when doubled.

How it works

Normal

Whispers only recognises lines that match one of a certain set of regexes. In the normal version, this reduces the program down to

> 1
>> Output 3

(i.e. the first and last lines don't match any regexes). The program then runs the last line, >> Output 3. This calls the 3rd line and outputs the result. However, as the reduced program only has 2 lines, this indexes modularly, returning the \$3 \mod 2\$th line (i.e. the first line), > 1. This is a basic nilad line which returns \$1\$, which is then outputted.

Doubled

The doubled program is

+1
> 1
>> Output 3
>> 1+1
> 1
>> Output 3
>> 1

Removing lines which don't match any regex, we get

> 1
>> Output 3
>> 1+1
> 1
>> Output 3

Again, the last line is run, telling the program to output the result of line 3. This time however, we do have a line 3 to output: >> 1+1. This does return \$2\$ but not because it evaluates \$1+1\$. Rather, it adds the value of line 1 to itself, which happens to be \$1\$.

Interestingly, this means that by changing > 1 to > n where \$n\$ is any number, the programs output \$n\$ and \$2n\$. For example

+1
> π
>> Output 3
>> 1

outputs \$\pi\$ normally or \$2\pi\$ when doubled

\$\endgroup\$
5
\$\begingroup\$

Google Sheets / Excel, 2 Bytes

The Trival Solution

+7

Or

+n

Such that n is an integer between 1 and 9, inclusive.

Google Sheets and Excel both will take a leading + or - and evaluate them down to = or =-, respectively if they are the leading character of a cells formula text. As a result, -n, such that n is an integer between 1 and 9, inclusive, is a valid negative equivalent of the above

As a single formula this evaluates to a call stack that looks a little something like

+7
=7
7

However when this worksheet formula is doubled this call stack evaluates down to

+7+7
=7+7
=14
\$\endgroup\$
5
\$\begingroup\$

vJASS (Warcraft 3), 150 bytes

//! inject main
set bj_randDistCount=bj_randDistCount+1
call ClearTextMessages()
call BJDebugMsg(I2S(bj_randDistCount))
//! dovjassinit
//! endinject

prints 1

//! inject main
set bj_randDistCount=bj_randDistCount+1
call ClearTextMessages()
call BJDebugMsg(I2S(bj_randDistCount))
//! dovjassinit
//! endinject
//! inject main
set bj_randDistCount=bj_randDistCount+1
call ClearTextMessages()
call BJDebugMsg(I2S(bj_randDistCount))
//! dovjassinit
//! endinject

prints 2

Explanation:

  • bj_randDistCount is a non-constant integer variable. Also, it has the shortest variable name you may find in blizzard.j.
  • ClearTextMessages() clears all text messages in your in-game screen.
  • I2S(int whichInt) -> string converts from integer to string
  • BJDebugMsg(string str) prints text on your in-game screen.
\$\endgroup\$
4
\$\begingroup\$

Pyth, 3 bytes

s[1

sums a list

Try it!

Double-try it

\$\endgroup\$
4
\$\begingroup\$

Charcoal, 7 bytes

PIL⊞Oυω

Try it online! Appends the empty string to the empty list and prints the length of the result (1) in decimal without moving the cursor. When doubled, the empty string gets appended twice so the length is now 2, which then overwrites the 1. Try it online! In verbose syntax, this is Multiprint(Cast(Length(PushOperator(u, w))));.

\$\endgroup\$
1
  • 7
    \$\begingroup\$ When I look at the code, it looks like it says "pillow"! \$\endgroup\$
    – Cort Ammon
    Jul 16, 2017 at 5:43
4
\$\begingroup\$

Self-modifying Brainfuck, 7 bytes

<-<201/

or doubled:

<-<201/<-<201/

Outputs 1 and 2 respectively.

The idea is simple: we use Self-modifying Brainfuck's self-modifying capability to make sure that the printing command only happens at the end of the full program.

Try it online!

Try it online, doubled!

\$\endgroup\$
4
\$\begingroup\$

Little Man Computer, 20 bytes (source)

LDA 1
ADD 5
OUT
HLT

Online Emulator (Flash)

\$\endgroup\$
1
  • 1
    \$\begingroup\$ Wowee never thought i'd have to see LMC again after I finished my a levels ... lovely little answer \$\endgroup\$
    – space junk
    Jul 19, 2017 at 11:09
4
\$\begingroup\$

bash, 16 bytes

a simple one:

wc -c<$0;exit 0;

First program: Try it online!

Second program: Try it online!

\$\endgroup\$
5
  • \$\begingroup\$ Thanks @Step-hen for the 2 TIO, I tried to use the site myself while writing the answer, but nothing happened when I pressed the run button (no output on my own attempts to set it up... weird as it was identical to yours...). Thanks for putting those 2 working links. \$\endgroup\$ Jul 19, 2017 at 15:31
  • \$\begingroup\$ No problem, I believe something is going wonky with TIO's backend right now (Dennis was talking about DOS attempts) so it's working on and off, sometimes it acts like it is infinitely looping. \$\endgroup\$
    – Stephen
    Jul 19, 2017 at 15:33
  • \$\begingroup\$ @StepHen: this looks like what was happening to me indeed (play button was looping). Thanks fo the info. Maybe not a DOS but just someone putting a script there that requires too much processing power? (Hanlon's razor : "Never attribute to malice that which is adequately explained by stupidity" ^^ ) \$\endgroup\$ Jul 19, 2017 at 15:34
  • \$\begingroup\$ wc is not part of bash, so should be mentioned in the title line. And I see no bashism so think, this will run on sh+wc too. \$\endgroup\$
    – user19214
    Mar 16, 2018 at 4:03
  • \$\begingroup\$ This for 10 bytes. \$\endgroup\$ Apr 3, 2021 at 18:59
4
\$\begingroup\$

Python 2, 24 bytes

'+1#';exec'print 1''' ''

Abusing string syntax.

\$\endgroup\$
4
\$\begingroup\$

Powershell, 2 bytes

+1

It's a full Powershell program. The output has printed to STDOUT.

\$\endgroup\$
4
\$\begingroup\$

Brachylog, 8 bytes

w₆-₇ℕ~l"

Try it online! Try it online!Try it online!

Although Brachylog has implicit function output, full programs won't automatically print without being given arguments, making this challenge a bit more interesting.

w₆          Declaratively write a number
  -₇        which minus 7
    ℕ       is a whole number (so length won't throw an error)
     ~l     equal to the length of
       "    an (implicitly terminated) empty string.

Doubling the code turns the empty string into a string of length 7, changing the printed output from 7 to 14.

\$\endgroup\$
4
\$\begingroup\$

Python 2, 27 bytes

+7
try:_
except:_=7;print _

Try it online!

Try it doubled!

\$\endgroup\$
4
\$\begingroup\$

Vyxal, 1 byte

Try it Online!

Doubled:

››

Try it Online! Try it Online!

Increments the top of the stack. Since the stack is empty, 0 is incremented instead, outputting 1. When doubled, 0 is incremented twice, outputting 2.

\$\endgroup\$
4
\$\begingroup\$

K (ngn/k), 3 bytes

+/1

Try it online!


+/1 - sum 1. returns 1

+/1+/1 - rightmost +/1 evaluates to 1 (as above), giving +/1 1, i.e. sum the vector 1 1. returns 2

EDIT: above is incorrect (written when i had a bad understanding of how k is parsed). corrected explanation:

+/1+/1 is +/(1+/1), where the parenthesized expression is "sum 1 with a seed of 1", which evaluates to 2, which is passed to +/, returning 2

\$\endgroup\$
3
\$\begingroup\$

V, 4 bytes

øß.

Try it online!

Or Try it doubled!

\$\endgroup\$
3
\$\begingroup\$

Cubix, 6 bytes

@1u.2O

When run, this pushes 1, u-turns, Outputs as a number, and h@lts:

  @
1 u . 2
  O

When doubled, the cube is

    @ 1
    u .
2 O @ 1 u . 2 O
. . . . . . . .
    . .
    . .

which simply pushes 2, Outputs as a number, and h@lts.

Try it online!

\$\endgroup\$
3
  • \$\begingroup\$ While looking at the duplicate question for a bit of fun I came up with this ^5O@N. Also has the twist of printing out it's length :) \$\endgroup\$
    – MickyT
    Aug 30, 2017 at 2:10
  • \$\begingroup\$ @MickyT you should post that as your own answer! That's a super cool one :) \$\endgroup\$
    – Giuseppe
    Dec 15, 2017 at 19:54
  • \$\begingroup\$ Done, but found another byte which made it a bit more boring \$\endgroup\$
    – MickyT
    Dec 17, 2017 at 17:47
3
\$\begingroup\$

R, 2 bytes

+1

prints 1 and when doubled

+1+1

prints 2

\$\endgroup\$
2
  • 1
    \$\begingroup\$ or +T or +2 or... \$\endgroup\$
    – Giuseppe
    Jul 17, 2017 at 19:21
  • \$\begingroup\$ This is exactly the same as the J answer. \$\endgroup\$
    – Adalynn
    Aug 23, 2017 at 23:31
3
\$\begingroup\$

Fourier, 3 bytes

@^o

Try it Online!

Try it Doubled!

Explanation:

Undoubled:

@    - Clear screen
 ^   - Increment the accumulator (initialised to zero)
  o  - Output the value of the accumulator

Doubled:

@       - Clear screen
 ^      - Increment the accumulator (initialised to zero)
  o     - Output the value of the accumulator
   @    - Clear screen
    ^   - Increment the accumulator
     o  - Output the value of the accumulator
\$\endgroup\$
3
\$\begingroup\$

Ruby (REPL), 3 2 bytes

Must be run interactively for the implicit output:

+2

Outputs 2.

Doubled:

+2+2

Outputs 4.

2 and 4 are more interesting than 1 and 2

\$\endgroup\$
3
  • 3
    \$\begingroup\$ @MorganThrapp REPL answers are allowed, as long as they're clearly labeled as such. \$\endgroup\$
    – Dennis
    Jul 17, 2017 at 21:08
  • \$\begingroup\$ My bad. I haven't been actively recently and missed that. \$\endgroup\$ Jul 17, 2017 at 21:10
  • 1
    \$\begingroup\$ +2 is a byte shorter. \$\endgroup\$
    – m-chrzan
    Jul 19, 2017 at 4:38
3
\$\begingroup\$

R, 2 bytes

+T

Never expected to codegolf this much in R. Due to the +, R changes the T for a numeric, using 1 as default.

\$\endgroup\$
3
\$\begingroup\$

PHP, 26 bytes

<?=ob_clean()+ob_start()?>

Try it online!

Try it doubled!

Explanation

PHP can use an output buffer. This buffer has the facility to be cleaned without its contents ever being sent.

When the script is run just once, the output buffer has not initially been started and so cannot be cleaned, and ob_clean() returns false. The buffer is then successfully started and ob_start() returns true. false + true is really 0 + 1, and so the script echoes 1 into the buffer and ends with the buffer being outputted.

If the script is doubled then this first 1 is not output but is still in the buffer when the second half of the doubled code starts. The output buffer is now cleaned, the 1 is lost, and ob_clean() this time returns true. Another output buffer is then started (they are, in fact, stacked) and ob_start() again returns true, so this time we have true + true, which is 1 + 1, and so 2 is sent to the output buffer and then on to the actual output when the script ends.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.