Dayz
Dayz

Reputation: 269

Create indexed array of filtered and trimmed elements

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
)

Upvotes: 1

Views: 761

Answers (2)

mickmackusa
mickmackusa

Reputation: 48070

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().

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 I've added spaces and empty values):

$officials_arr = [' off1' , 'off2' , '' , 'off3 ' , null];
//           space ^      empty string^   space^    ^null

Code: (Demo)

$result = [];
array_walk(
    $officials,
    function($v) use (&$result) {
        $v = trim((string) $v);
        if (strlen($v)) {
            $result[] = $v;
        }
    }
);
var_export($result);

Output:

array (
  0 => 'off1',
  1 => 'off2',
  2 => 'off3',
)

Upvotes: 1

user7391763
user7391763

Reputation:

Use array_values, see here.

$officials = array_values($officials);

Upvotes: 3

Related Questions