views:

184

answers:

3

I have the following array:

$person = array('first_name' => 'Fred', 'last_name' => 'Flintstone');

I want to change/pad the keys so the array will end up as (note extra colons):

$person = array('::first_name::' => 'Fred', '::last_name::' => 'Flintstone');

For some reason I'm drawing a blank on the simplest way to do this

+3  A: 

I don't know the simplest way, but the quickest way off the top of my head would be to just loop through.

foreach($person as $key=>$value) {
$newArray['::' . $key .'::'] = $value;

}

I guess you could even do

function tokenize($person)
{
    foreach($person as $key=>$value) {
    $newArray['::' . $key .'::'] = $value;    
    }
    return $newArray;
}

$person = array('first_name' => 'Fred', 'last_name' ='Flintstone');
$newPerson = array_map("tokenize", $person);
print_r($newPerson);
Laykes
The `tokenize` function does not work as `array_map` will pass the elements of the $person array to it and not the $person array itself.
Gordon
Ah okay. I wasn't aware of that. Well you could always array_keys() as well as array_values(). Thanks for the comments.
Laykes
+1  A: 

Variation from Laykes solution, just without creating a new array:

foreach($array as $key => $val) {
    $array["..$key.."] = $val;
    unset($array[$key]);
}

I assume you want to do this because you are replacing placeholders in your template with something like this:

$template = str_replace(array_keys($person), $person, $template);

If so, keep in mind that you are iterating twice over $person then. One time to change the keys and another time to get the keys. So it would be more efficient to replace the call to array_keys() with a function that return the keys as padded values, e.g. something like

function array_keys_padded(array $array, $padding) {
    $keys = array();
    while($key = key($array)) {
        $keys[] = $padding . $key . $padding;
        next($array);
    }
    return $keys;
}
// Usage
$template = str_replace(array_keys_padded($person, '::'), $person, $template);

But then again, you could just as well do it with a simple iteration:

foreach($person as $key => $val) {
    str_replace("::$key::", $val, $template);
}

But disregard this answer if you are not doing it this way :)

Out of curiosity, how are your users actually providing the array?

Gordon
Users are providing the array as a tag list in a form. Just like the tags you put on a stackoverflow question.
k00k
A: 

You can also do:

<?php
$person = array('first_name' => 'Fred', 'last_name' =>'Flintstone');

$keys = array_keys($person); // array of keys.

for($i=0;$i<count($person);$i++) {
    $keys[$i] = "::$keys[$i]::"; // change each key.
}
// recreate array using changed keys.
$person = array_combine($keys,array_values($person)); 

var_dump($person);
?>

Output:

array(2) {
  ["::first_name::"]=>
  string(4) "Fred"
  ["::last_name::"]=>
  string(10) "Flintstone"
}
codaddict