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...
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.
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.
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 )
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With