Search code examples
phparraysdestructuringvariable-declarationspread-syntax

Destructuring an array using spread operator on left side of assignment to collect all remaining elements in a single variable


I want to perform Destructuring in php just like in javascript code below:

[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(a,b,rest);

Output:

10 20 [ 30, 40, 50 ]

How can I preform that operation in php?

My php code is:

<?php
$array = [10, 20, 30, 40, 50]; 

// Using the list syntax:
//list($a, $b, $c[]) = $array;

// Or the shorthand syntax:
[$a, $b, $c[]] = $array;

echo "$a<br>$b<br>";
print_r ($c);
?>

Which prints:

10
20
Array ( [0] => 30 )

But I want "[ 30, 40, 50 ]" in $c


Solution

  • I did this using spread operator and function:

    function f1($a,$b,...$c) {
        return ['a' => $a, 'b' => $b, 'c' => $c];
    }
    $array = [10, 20, 30, 40, 50]; 
    extract (f1(...$array));
    echo "$a<br>$b<br>";
    print_r ($c);
    

    Please let me know if this is correct way to do it.