Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

153
Vistas
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 Respuestas
Responde la pregunta

0

Use array_values, see here.

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

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda