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...
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...
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);
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 )
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,
)
© 2022 - 2024 — McMap. All rights reserved.
attr_
from your array keys? What has this got to do withimplode()
? Shouldattr_my_prop
becomemy_prop
,prop
or something else? Most importantly, why? Can we see your "failing" code please? – Paradrop