Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Update

After the initial feedback I got that my question is unclear, I decided to start over and ask it with more context, and clearer details. See Many php mysqli queries from one prepared statement without knowing how many parameters

Sorry about the confusion.

Original Question

I'd like to dynamically turn an associative array:

$array =
[
    'key' => 'AX-2NV',
    'id' => 2
]

into an array of variables:

[$key,$id] // where $key='AX-2NV' and $id=2

When I have no control over the input array. The variable creation is simple enough with the extract function

extract($array); // will create the variables $key and $id

The challenge is how do I get the resulting variables in an array when I don't know ahead of time what the variable names or the input array size will be?

This may be irrelevant but the objective is to make a call to the function call_user_func_array and pass it the array [$key,$id] as the parameters of the function I'm calling. I've considered doing simply

call_user_func_array($function,array_values($array));

But I still need a handle to these variables for further processing, so just using the values and moving on is not an option.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
254 views
Welcome To Ask or Share your Answers For Others

1 Answer

You can make an array containing a list of all the keys from another array with array_keys().

extract() may have security implications, I hope this is some sort of hypothetical problem because otherwise you should be fetching the data you need from the array itself, and not converting its items into global variables.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...