Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - Variable names as Array Keys

I'm looking for something like the opposite of extract().

Say I have a few variables

$state = "FL";
$city = "Hollywood";
$zip = "33021";

How can I make an array that uses the variables' names as the array keys:

array( "state"=>"FL", "city"=>"Hollywood", "zip"=>"33021" );
like image 447
Alex V Avatar asked Nov 16 '11 04:11

Alex V


1 Answers

You should use the compact() function though. Such as:

$state = "FL";
$city = "Hollywood";
$zip = "33021";
$array = compact('state', 'city', 'zip');

Edit: Seems to do exactly what you need, don't know why you don't think you need it. If you're looking for something exactly opposite of extract(), such as taking all available variables and putting them into an array, you can't do that, because PHP would literally take all variables in the current scope and put them into the array. You have to specify which variables somehow.

like image 135
animuson Avatar answered Oct 03 '22 17:10

animuson