Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove prefix in array keys

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

like image 471
rat4m3n Avatar asked Dec 23 '11 09:12

rat4m3n


People also ask

How do you remove a prefix from an array?

map() is needed. you can also use . forEach() if you need to keep the original array. This solution strips the prefix of array strings by length of pre regardless of whether it matches the prefix of the strings in the array.

What is Array_keys () used for?

The array_keys() is a built-in function in PHP and is used to return either all the keys of and array or the subset of the keys. Parameters: The function takes three parameters out of which one is mandatory and other two are optional.


1 Answers

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 ) 
like image 160
Frosty Z Avatar answered Oct 11 '22 09:10

Frosty Z