How to remove prefix in array keys
Asked Answered
S

3

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...

Serapis answered 23/12, 2011 at 9:40 Comment(1)
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?Paradrop
J
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);

Jactitation answered 23/12, 2011 at 9:43 Comment(0)
F
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 ) 
Fm answered 23/12, 2011 at 9:47 Comment(0)
C
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,
)
Cytology answered 17/5, 2022 at 10:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.