交换两个函数执行顺序的简写

I'm looking for an abbreviated way to write the following logic in Php:

if condition do
   function b
   function a
else do
   function a
   function b

Or rather, a simple way to swap the order that functions a and b are executed.

This is what I've come up with so far:

!$swap && a(); // Where $swap is a boolean
b();
$swap && a();

A use case could be changing the rendering order of display output e.g. html.

You can do this with a loop consisting of two iterations. With an if/else containing each function calls as statements within the loop. A flag determines which function to run. After one iteration the flag is toggled, so next time the other function runs:

function a() {
    echo 'a';
}

function b() {
    echo 'b';
}

function c($flip = false) {

    for($i=0; $i<2; $i++) {
        if(! $flip) {
            a();
        } else {
            b();
        }
        $flip = ! $flip; // On next run the other statement will run
    }

}

c($flip = false);
c($flip = true);

// Outputs: abba

Or using the ternary operator:

function d($flip = false) {

    for($i=0; $i<2; $i++, $flip=!$flip) {
        !$flip ? a() : b();
    }

}

In a html view:

<?php for($i=0; $i<2; $i++) { if(! $flip) { // Change the block display order if flip is true. ?>

    <h2>Block Foo</h2>
    <p>...</p> 

<?php } else { ?>

    <h2>Block Bar</h2>
    <p>...</p>

<?php } $flip = !$flip; } ?>

The context being that I wrote a CMS module, and wanted a simple option for the end user to change the order of html, without overriding templates. I hope someone finds this useful.

If this where a question of Code Golf, I would try with one of these solutions:

$f = $condition ? ['a', 'b'] : ['b', 'a'];
$f[0]();
$f[1]();

or

$f = ['a', 'b'];
$f[$condition]();
$f[!$condition]();

Demo.

But in a normal php script there isn't a valid reason to do this.

You can put it in a ternary operator. condition ? When true : when false;. You might have to put when true and when false into functions if you have multiple lines of code.

You could add your function names to an array and then reverse the array if you wanted to execute them in reverse order. Like below:

$functions = ['a', 'b'];
$reverse = TRUE;

if( $reverse )
{
    $functions = array_reverse( $functions );
}

$functions[0]();
$functions[1]();

This is a good example of being too clever. Your first example looks great!

Remember that your code should be read by others (or yourself, a few weeks from now), and duplicating a little code to increase readability is almost always worth it.