15

I try to remove a prefix in array keys and every attempt is failing. What I want to achieve is to:

Having: Array ( [attr_Size] => 3 [attr_Colour] => 7 )

To Get: Array ( [Size] => 3 [Colour] => 7 )

Your help will be much appreciated...

PhoneixS
  • 10,574
  • 6
  • 57
  • 73
rat4m3n
  • 1,201
  • 2
  • 16
  • 23
  • 6
    So you just want to remove `attr_` from your array keys? What has this got to do with `implode()`? Should `attr_my_prop` become `my_prop`, `prop` or something else? Most importantly, why? Can we see your "failing" code please? – Wesley Murch Dec 23 '11 at 09:42

3 Answers3

4

One of the ways To Get:Array ( [Size] => 3 [Colour] => 7 ) From your Having: Array ( [attr_Size] => 3 [attr_Colour] => 7 )

$new_arr = array();
foreach($Your_arr as $key => $value) {

list($dummy, $newkey) = explode('_', $key);
$new_arr[$newkey] = $value;

}

If you think there'll be multiple underscores in keys just replace first line inside foreach with list($dummy, $newkey) = explode('attr_', $key);

mega6382
  • 9,211
  • 17
  • 48
  • 69
TigerTiger
  • 10,590
  • 15
  • 57
  • 72
4

If I understood your question, you don't have to use implode() to get what you want.

define(PREFIX, 'attr_');

$array = array('attr_Size' => 3, 'attr_Colour' => 7);

$prefixLength = strlen(PREFIX);

foreach($array as $key => $value)
{
  if (substr($key, 0, $prefixLength) === PREFIX)
  {
    $newKey = substr($key, $prefixLength);
    $array[$newKey] = $value;
    unset($array[$key]);
  }
}

print_r($array); // shows: Array ( [Size] => 3 [Colour] => 7 ) 
Maxime Pacary
  • 22,336
  • 11
  • 85
  • 113
0

Because the first character that you'd like to retain in each key starts with an uppercase letter, you can simply left-trim lowercase letters and underscores and voila. To create a "mask" of all lowercase letters and the underscore, you could use a..z_, but because attr_ is the known prefix, _art will do. My snippet, admittedly, is narrowly suited to the asker's sample data, does not call explode() to create a temporary array, and does not make multiple function calls per iteration. Use contentiously.

Code: (Demo)

$array = [
    'attr_Size' => 3,
    'attr_Colour' => 7
];

$result = [];
foreach ($array as $key => $value) {
    $result[ltrim($key, '_art')] = $value;
}
var_export($result);

Output:

array (
  'Size' => 3,
  'Colour' => 7,
)
mickmackusa
  • 43,625
  • 12
  • 83
  • 136