Strip whitespace from associative array Keys
If you're looking at this and need to remove or replace spaces that are not at beginning or end of key, you can pass an array to str_replace
:
$my_array = array( 'one 1' => '1', 'two 2' => '2' );
$keys = str_replace( ' ', '', array_keys( $my_array ) );
$results = array_combine( $keys, array_values( $my_array ) );
Example: https://glot.io/snippets/ejej1chzg3
Try this function will help you..
function trimArrayKey(&$array)
{
$array = array_combine(
array_map(
function ($str) {
return str_replace(" ", "_", $str);
},
array_keys($array)
),
array_values($array)
);
foreach ($array as $key => $val) {
if (is_array($val)) {
trimArrayKey($array[$key]);
}
}
}
Hope this helps...
The accepted answer didn't solve the problem for my particular scenario, but this did the trick.
$temp = array();
foreach ($stripResults as $key => $value) {
$temp[trim($key)] = trim($value);
}
$stripResults = $temp;
Keys must be processed separately:
$a = array_map('trim', array_keys($stripResults));
$b = array_map('trim', $stripResults);
$stripResults = array_combine($a, $b);