Skip to content
Advertisement

Destructuring in php

Is it possible to use javascript like destructuring to create an associative array from variables with variable names as keys in PHP… in javascript I can do

 const fn = (name, age, purpose) => {
    return {name, age, purpose}
 }
 fn("Akins", 23, "Greatness") // {name: "Akins", age: 23, purpose: "Greatness"}

Currently I am stick to repetitive way

function fn($name, $age, $purpose) {
     return [
         'name'    => $name,
         'age'     => $age,
         'purpose' => $purpose
     ];
}

Can anyone help, it will save me a whole lot of typing?

Advertisement

Answer

There’s no need to create your own function for this, one already exists:

$name    = "Jason";
$age     = 25;
$purpose = "To have fun?";

$person  = compact('name', 'age', 'purpose');

print_r($person);

Ouptut:

Array
(
    [name] => Jason
    [age] => 25
    [purpose] => To have fun?
)
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement