Question

I'm working with an array of data that I've changed the names of some array keys, but I want the data to stay the same basically... Basically I want to be able to keep the data that's in the array stored in the DB, but I want to update the array key names associated with it.

Previously the array would have looked like this: $var_opts['services'] = array('foo-1', 'foo-2', 'foo-3', 'foo-4');

Now the array keys are no longer prefixed with "foo", but rather with "bar" instead. So how can I update the array variable to get rid of the "foos" and replace with "bars" instead?

Like so: $var_opts['services'] = array('bar-1', 'bar-2', 'bar-3', 'bar-4');

I'm already using if(isset($var_opts['services']['foo-1'])) { unset($var_opts['services']['foo-1']); } to get rid of the foos... I just need to figure out how to replace each foo with a bar.

I thought I would use str_replace on the whole array, but to my dismay it only works on strings (go figure, heh) and not arrays.

Was it helpful?

Solution

The idea:

  1. Get a list of all your array keys
  2. Modify each one of them as you choose
  3. Replace the existing keys with the modified ones

The code:

$keys = array_keys($arr);
$values = array_values($arr);
$new_keys = str_replace('foo', 'bar', $keys);
$arr = array_combine($new_keys, $values);

What this actually does is create a new array which has the same values as your original array, but in which the keys have been changed.

Edit: updated as per Kamil's comment below.

OTHER TIPS

For the values you've provided $var_opts['services'] = array('foo-1', 'foo-2', 'foo-3', 'foo-4');

var_dump($var_opts['services']);

foreach($var_opts['services'] as &$val) {
    $val = str_replace('foo', 'bar', $val);
}
unset($val);

var_dump($var_opts['services']);

or if you want to change the actual keys

$var_opts['services'] = array('foo-1'   => 1, 'foo-2'   => 2, 'foo-3'   => 3, 'foo-4'   => 4);
var_dump($var_opts['services']);
foreach($var_opts['services'] as $i => $val) {
    unset($var_opts['services'][$i]);
    $i = str_replace('foo', 'bar', $i);
    $var_opts['services'][$i] = $val;
}

var_dump($var_opts['services']);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top