4

I am assigning an array with the $variables(have different name) that have some values like:

array($one, $two, $three);

now i am a searching a way that is there any way to assign this above array with key name same as variable name directly, finally i want to make this array like:

array(
      "one" => $one, 
      "two" => $two, 
      "three" => $three
)

if this can possible at the time of assigning array with the variable then i would be good for me then i can easily extract() this array and i don't have to do operation to open this array and assigning these values with the $variable name, if any function() exist for that then it will be good, please help if any one knows

0

2 Answers 2

7

compact is the inverse of extract. Use it like this :

$array = compact ('one', 'two', 'three');

This will look for the variables named 'one', 'two', 'three', and does exactly what you are looking for.

Sign up to request clarification or add additional context in comments.

1 Comment

This is what i am searching for thanks @Lorenz Meyer
0

Here is a limitation you have add 2 times get_defined_vars();

PHP code demo

<?php

$someVariable=1;
$someVariable=2;
$someVariable=3;
$definedOld=get_defined_vars();//this will bring all variables defined till now.

$one="test1";
$two="test2";
$three="test3";

$definedNew = get_defined_vars();//this will bring all variables defined till now.

$variables=array_diff($definedNew,$definedOld);//finding the difference
print_r($variables);

1 Comment

i know this can be done by some logics but i am searching for a function

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.