Arrays and the PITA they can be!

Although it doesn’t happen very often, there are a few times when I need to push the values of an array to the keys. Now I know what you may be thinking, why the H E double hockey sticks would anybody need to do that. The real answer is, I have no idea, but I needed to one time, and I created a function just for that. Just go with it… It is much gooder!

Here is an example:
array (“name”, “address”, “city”, “state”, “zip”, “phone”, “email”);

Now I want that to become:
array (“name”=>"", “address”=>"", “city”=>"", “state”=>"", “zip”="", “phone”=>"", “email”=>"");

Here is cute little script to do just that:

[php]
function values2keys($arr, $value=1){
$new = array();
while (list($k,$v) = each($arr)){
$v = trim($v);
if ($v != ‘’){
$new[$v] = $value;
}
}
return $new;
}
[/php]

Here is another variant

[php]$list = array(‘name’, ‘address’, ‘city’, ‘state’, ‘zip’, ‘phone’, ‘email’);

$data = array_fill_keys($list, ‘’);

var_dump($data);

/*
array(7) {
[“name”]=>
string(0) “”
[“address”]=>
string(0) “”
[“city”]=>
string(0) “”
[“state”]=>
string(0) “”
[“zip”]=>
string(0) “”
[“phone”]=>
string(0) “”
[“email”]=>
string(0) “”
}
*/[/php]

Thanks Jim,
I think I wrote that back in PHP 4.x since it was dated 2001 in my file list… Since this is something I don’t mess with that much I never really looked for a replacement. But you win the much gooder award :smiley:

Sponsor our Newsletter | Privacy Policy | Terms of Service