I have an associative that outputs whitespace in the key and value. I need to strip the whitespace from first letter and also the last letter and keep the space inbetween.
I have tried
$stripResults = array_filter(array_map('trim', $results));
This strips the value perfectly but not the key. How do I strip the key and value?
Method 1: Using unset() function: The unset() function is used to unset a key and its value in an associative array. print_r( $arr ); ?> Method 2: Using array_diff_key() function: This function is used to get the difference between one or more arrays.
Method 1: Using trim() and array_walk() function: trim() Function: The trim() function is an inbuilt function which removes whitespaces and also the predefined characters from both sides of a string that is left and right.
If you want to delete an element from an array you can simply use the unset() function. The following example shows how to delete an element from an associative array and numeric array.
Just make a note of the old value, use unset to remove it from the array then add it with the new key and the old value pair. Save this answer.
Answer: Use the PHP array_keys() function You can use the PHP array_keys() function to get all the keys out of an associative array.
Using unset() Function: The unset() function is used to remove element from the array. The unset function is used to destroy any other variable and same way use to delete any element of an array. This unset command takes the array key as input and removed that element from the array.
No, you cannot have multiple of the same key in an associative array. You could, however, have unique keys each of whose corresponding values are arrays, and those arrays have multiple elements for each key.
Keys must be processed separately:
$a = array_map('trim', array_keys($stripResults));
$b = array_map('trim', $stripResults);
$stripResults = array_combine($a, $b);
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...
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