PHP or Laravel Helper Function to Collect Variables Into Array

199 views Asked by At

I vaguely remember there being a PHP or Laravel helper function that collects variables into a named array, using the variable names as the array keys.

What was the name of that function again?

With

$foo = 1;
$bar = 2;

this call

some_function($foo, $bar);

would return

[
    "foo" => 1,
    "bar" => 2
]
3

There are 3 answers

0
Alexey Mezenin On BEST ANSWER

Use compact():

compact('foo', 'bar');
0
Md Rasel Ahmed On

Use combine()

The combine method combines the keys of the collection with the values of another array or collection:

$collection = collect(['name', 'age']);

$combined = $collection->combine(['George', 29]);

$combined->all();

// ['name' => 'George', 'age' => 29]
0
Dhaval Bhavsar On

You can use PHP function array_combine please visit these link array_combine

$array_key = ['name','age'];

$array_value = ['George', 29];

$final_array = array_combine($array_key,$array_value);

you will get final result

[
    "name" => "George",
    "age" => 29
]

Note :- Both array must be same size of array