Question

is there any way to post or per increment multiple variables with one increment operator. i have 4 values on which i need to increment one value

$a = 1; $b = 3; $c = 45; $d = 10;

normally we use this method but instead of incrementing them individually like

++$a; ++$b; ++$c; ++$d;

can i do something like encapsulate them in brackets and then globally perform increment on them

++($a, $b, $c, $d);

i have tried the above statement but it don't work.

Was it helpful?

Solution

you can use array_map along with an array of referenced variables

array_map(function(&$var){  $var++; }, array(&$a, &$b, &$c, &$d));

OTHER TIPS

You can write a function that takes arguments by reference:

function inc_all(&$arg1, &$arg2 = 0, &$arg3 = 0, &$arg4 = 0) {
    $arg1++;
    $arg2++;
    $arg3++;
    $arg4++;
}

inc_all($a, $b, $c, $d);

You need to code the function for the maximum number of variables you need to increment at once, because it's not possible to pass by reference to a function that uses func_get_args to process arbitrary length argument lists.

No, that is not possible. You will just have to waste the additional statements to increment them one by one.

Something that is applicable in other situations is that you can set multiple values at once. For example,
$a = $b = $c = 10; will set both $a, $b and $c to 10.

Since php 5.6 it is possible to use variadics and handle variable number of arguments in one function:

function increment(&...$arguments)
{
    foreach($arguments as &$arg){
        ++$arg;
    }
}
increment($a);
increment($b, $c);
increment($x, $y, $z);

Original answer:

One other example, without references:

extract(array_map(function($v){return ++$v;}, compact(array('a','b','c','d'))));

Using help from this code, I managed to make a slightly more dynamic version of this answer

It's quite a hackjob, but this example would do the trick for up to 9 arguments.

// Workaround from
// http://www.php.net/manual/en/function.func-get-args.php#110030
function func_get_args_byref() {
    $trace = debug_backtrace();
    return $trace[1]['args'];
}

// ``&x=0'', required to pass arg as reference
// You can increase the amount of maximum arguments by adding ``&$x=0''
function inc( &$x=0,&$x=0,&$x=0,&$x=0,&$x=0,&$x=0,&$x=0,&$x=0,&$x=0 ) {
    $arguments = func_get_args_byref();
    foreach ($arguments as &$arg) ++$arg;
}

$a = 0; $b = 3; $c = 45; $d = 10;

inc($a, $b, $c, $d); // a = 1, b = 4, c = 46, d = 11
inc($b, $d);         // a = 1, b = 5, c = 46, d = 12
inc($c, $d);         // a = 1, b = 5, c = 47, d = 13
inc($a, $a, $c);     // a = 3, b = 5, c = 48, d = 13
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top