I need to change the index of array after array filtering and trimming white spaces.
$officials_arr= $this->input->post('officials');
$officials = array_filter(array_map('trim', $officials_arr));
print_r($officials);
Desired output:
(
[0] => off1
[1] => off2
[2] => off3
)
But I got output as :
Array
(
[0] => off1
[1] => off2
[3] => off3
)
Instead of using: $officials=array_values(array_filter(array_map('trim',$officials_arr))); (...which by the way will remove all null, false-y, zero-ish values from your array -- this is the greedy default behavior of array_filter()) I recommend that you generate the desired output in a more reliable and efficient way using just array_walk() and strlen() in a one-liner. My method will remove zero-length strings (null/false/empty), trim spaces from both sides of each value, and re-index the result array.
Input (notice, notice I've added spaces and empty values):
$officials_arr=[' off1' , 'off2' , '' , 'off3 ' , null];
space ^ empty string^ space^ ^null
Method:
array_walk($officials_arr,function($v)use(&$officials){if(strlen($v)){$officials[]=trim($v);}});
var_export($officials);
Output:
array ( 0 => 'off1', 1 => 'off2', 2 => 'off3', )
Breakdown:
array_walk( // iterate each element in the input array
$officials_arr, // input array
function($v) // temporary variable name for each element
use(&$officials){ // declare the output array, & means "modifiable"
if(strlen($v)){ // check if element value has any characters
$officials[]=trim($v); // push qualifying value into output array
}
}
);