Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

148
Views
change index after array filtering and trimming

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
)
over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Use array_values, see here.

$officials = array_values($officials);
over 4 years ago · Santiago Trujillo Report

0

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
        }
    }
);
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!