220

I have an array as follows

$fruit = array('  apple ','banana   ', ' , ',     '            cranberry ');

I want an array which contains the values without the white spaces on either sides but it can contain empty values how to do this in php.the output array should be like this

$fruit = array('apple','banana', ',', 'cranberry');

15 Answers 15

613

array_map and trim can do the job

$trimmed_array = array_map('trim', $fruit);
print_r($trimmed_array);
8
  • 6
    Excellent. Much simpler than using array_walk or a foreach loop
    – Ryan
    Commented Nov 19, 2011 at 5:33
  • 10
    ravisoni, you would map that function; array_map('rtrim', $fruit);. Hope it helps :)
    – Jongosi
    Commented Nov 26, 2013 at 17:12
  • this one better $fruit= array_map('trim', $fruit); Commented Mar 18, 2017 at 10:18
  • 1
    What happens if one of the fruits is an array of f.e. Exotic Fruits?
    – Halfacht
    Commented Jun 21, 2018 at 13:36
  • 1
    @Jongosi 'rtrim' though would just strip the whitespaces at the end of the string while 'trim' is more robust in stripping white spaces both before and after the string.
    – 2147483647
    Commented Jun 22, 2023 at 13:54
14

Multidimensional-proof solution:

array_walk_recursive($array, function(&$arrValue, $arrKey){ $arrValue = trim($arrValue);});
1
  • Thanks! Confirming this will actually trim the nested contents too, and not ignore them or set to null. Commented Jun 17, 2020 at 12:22
9

array_walk() can be used with trim() to trim array

<?php
function trim_value(&$value) 
{ 
    $value = trim($value); 
}

$fruit = array('apple','banana ', ' cranberry ');
var_dump($fruit);

array_walk($fruit, 'trim_value');
var_dump($fruit);

?>

See 2nd example at http://www.php.net/manual/en/function.trim.php

4

I had trouble with the existing answers when using multidimensional arrays. This solution works for me.

if (is_array($array)) {
    foreach ($array as $key => $val) {
        $array[$key] = trim($val);
    }
}
3

If the array is multidimensional, this will work great:

//trims empty spaces in array elements (recursively trim multidimesional arrays)
function trimData($data){
   if($data == null)
       return null;

   if(is_array($data)){
       return array_map('trimData', $data);
   }else return trim($data);
}

one sample test is like this:

$arr=[" aaa ", " b  ", "m    ", ["  .e  ", "    12 3", "9 0    0 0   "]];
print_r(trimData($arr));
//RESULT
//Array ( [0] => aaa [1] => b [2] => m [3] => Array ( [0] => .e [1] => 12 3 [2] => 9 0 0 0 ) )
3

array_map('trim', $data) would convert all subarrays into null. If it is needed to trim spaces only for strings and leave other types as it is, you can use:

$data = array_map(
    function ($item) {
        return is_string($item) ? trim($item) : $item;
    },
    $data
);
2

If you want to trim and print one dimensional Array or the deepest dimension of multi-dimensional Array you should use:

foreach($array as $key => $value)
{
    $array[$key] = trim($value);
    print("-");
    print($array[$key]);
    print("-");
    print("<br>");
}

If you want to trim but do not want to print one dimensional Array or the deepest dimension of multi-dimensional Array you should use:

$array = array_map('trim', $array);
2

If you don't want to lose elements of an associative array, DONT use array_walk or array_map!

A slightly shorter version of the foreach solution:

foreach($array as &$val)
   $val = trim($val);

This works for associative arrays.

1
$fruit= array_map('trim', $fruit);
1
0
function generateRandomString($length = 10) {
    $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}

function generateRandomSpaces() {
    $output = '';
    $i = rand(1, 10);
    for ($j = 0; $j <= $i; $j++) {
        $output .= " ";
    }   

    return $output;
}

// Generating an array to test
$array = [];
for ($i = 0; $i <= 1000; $i++) {
    $array[] = generateRandomSpaces() . generateRandomString(10) . generateRandomSpaces(); 
}

// ARRAY MAP
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    $trimmed_array=array_map('trim',$array);
}
$time = (microtime(true) - $start);
echo "Array map: " . $time . " seconds\n";

// ARRAY WALK
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    array_walk($array, 'trim');
}
$time = (microtime(true) - $start);
echo "Array walk    : " . $time . " seconds\n"; 

// FOREACH
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    foreach ($array as $index => $elem) {
        $array[$index] = trim($elem);
    }
}
$time = (microtime(true) - $start);
echo "Foreach: " . $time . " seconds\n";

// FOR
$start = microtime(true);
for ($i = 0; $i < 100000; $i++) {
    for ($j = 0; $j < count($array) - 1; $j++) { 
        $array[$j] = trim($array[$j]);
    }
}
$time = (microtime(true) - $start);
echo "For: " . $time . " seconds\n";

The output of the code above is:

Array map: 8.6775720119476 seconds
Array walk: 10.423238992691 seconds
Foreach: 7.3502039909363 seconds
For: 9.8266389369965 seconds

This values of course may change but I would say foreach is the best option.

1
  • Is there an answer to the original question in all of this code and text?
    – Krista K
    Commented May 16, 2018 at 4:47
0

Trim in array_map change type if you have NULL in value.

Better way to do it:

$result = array_map(function($v){ 
  return is_string($v)?trim($v):$v; 
}, $array);
0

simply you can use regex to trim all spaces or minify your array items

$array = array_map(function ($item) {
    return preg_replace('/\s+/', '', $item);
}, $array);
0
function trim_value(&$value) 
    { 
        $value = trim($value); 
    }
    
    
    // ut_sreco_dis Module
    public function disExcelUpload($file=""){
    
        ini_set('MAX_EXECUTION_TIME', -1);
        ini_set('memory_limit', '-1');   
    
        $file_upload    = $file;
    
        if (isset($file_upload) && !empty($file_upload)){ 
    
        //You can add directly the Composer Autoloder in your controller: 
        require FCPATH . 'vendor/autoload.php';
    
        try{   
            $objPHPExcel = PHPExcel_IOFactory::load($file_upload);   
        }   
        catch (Exception $e){
            die('Error loading file "' . pathinfo($file_upload, PATHINFO_BASENAME) . '": '.@$e->getMessage()); 
        }   
    
        $allDataInSheet         = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);  
        $sheet                  = $objPHPExcel->getSheet(0);  
        $highestRow             = $sheet->getHighestRow();  
        $highestCol             = $sheet->getHighestColumn();  
        $highestco              = $sheet->getHighestDataColumn();  
        $arrayCount             = count($allDataInSheet);   
        $now                    = date("Y-m-d H:i:s");      
        $flag = 0;
    
        $check_template = array(
            'A' => 'FIN_ID',
            'B' => 'SECCODE',
            'C' => 'SCHEME_NO',
            'D' => 'SEC_SCH',
            'E' => 'DISNO',
            'F' => 'DISQTY',
            'G' => 'BILLQTY',
            'H' => 'BILLREF',
            'I' => 'BILLDT',       
        );
    
            $input_template = $allDataInSheet[1];
    
            array_walk($input_template, $this->trim_value);
    
            $result = array_diff($check_template, $input_template);
    
            if(empty($result))
            {
                $this->srObject->truncTableDis();
    
                # loop for inserting data 
                for ($i = 2,$j=0; $i <= $highestRow; $i++){
    
                    $db_ch_ot = 64;
    
                    $fin_id         = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                    $sec_code       = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                    $sch_no         = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                    $sec_sch        = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                    $dis_no         = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                    $dis_qty        = trim($allDataInSheet[$i][chr(++$db_ch_ot)]); 
                    $bill_qty       = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                    $bill_ref       = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);             
                    $bill_dt        = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
    
                    if(empty($bill_dt)){
                        $bill_dt = null;
                    }else{
                        $dip_dt = date("Y-m-d",strtotime($bill_dt));                    
                    }                
    
                    $dt             = date('Y-m-d H:i:s');
                    
                    $insert_data = array(  
                        "fin_id_data"           => $fin_id,
                        "sec_code_data"         => $sec_code,
                        "sch_no_data"           => $sch_no,
                        "sec_sch_data"          => $sec_sch,
                        "dis_no_data"           => $dis_no,                   
                        "dis_qty_data"          => $dis_qty,                   
                        "bill_qty_data"         => $bill_qty,
                        "bill_ref_data"         => $bill_ref,                   
                        "bill_dt_data"          => $bill_dt,                    
                        "created_at_data"       => $dt,
                        "updated_at_data"       => $dt,           
                    );
                    
                    if($this->srObject->insertSdisData($insert_data))
                    {
                        ++$flag;
                    }
    
    
                } //loop close  
            } else {
                $this->session->set_flashdata('error', 'Error. Invalid Excel Template');
                redirect(site_url('schill-bill-checking-suuti/sreco'));
            }  
    
            $this->session->set_flashdata('success', 'File Uploaded Successfully ..'.' New Record Inserted : '.$flag);
            redirect(site_url('schill-bill-checking-suuti/sreco'));
    
            
        }
        
    }
-2
function trim_value(&$value) 
{ 
    $value = trim($value); 
}


// ut_sreco_dis Module
public function disExcelUpload($file=""){

    ini_set('MAX_EXECUTION_TIME', -1);
    ini_set('memory_limit', '-1');   

    $file_upload    = $file;

    if (isset($file_upload) && !empty($file_upload)){ 

    //You can add directly the Composer Autoloder in your controller: 
    require FCPATH . 'vendor/autoload.php';

    try{   
        $objPHPExcel = PHPExcel_IOFactory::load($file_upload);   
    }   
    catch (Exception $e){
        die('Error loading file "' . pathinfo($file_upload, PATHINFO_BASENAME) . '": '.@$e->getMessage()); 
    }   

    $allDataInSheet         = $objPHPExcel->getActiveSheet()->toArray(null, true, true, true);  
    $sheet                  = $objPHPExcel->getSheet(0);  
    $highestRow             = $sheet->getHighestRow();  
    $highestCol             = $sheet->getHighestColumn();  
    $highestco              = $sheet->getHighestDataColumn();  
    $arrayCount             = count($allDataInSheet);   
    $now                    = date("Y-m-d H:i:s");      
    $flag = 0;

    $check_template = array(
        'A' => 'FIN_ID',
        'B' => 'SECCODE',
        'C' => 'SCHEME_NO',
        'D' => 'SEC_SCH',
        'E' => 'DISNO',
        'F' => 'DISQTY',
        'G' => 'BILLQTY',
        'H' => 'BILLREF',
        'I' => 'BILLDT',       
    );

        $input_template = $allDataInSheet[1];

        array_walk($input_template, $this->trim_value);

        $result = array_diff($check_template, $input_template);

        if(empty($result))
        {
            $this->srObject->truncTableDis();

            # loop for inserting data 
            for ($i = 2,$j=0; $i <= $highestRow; $i++){

                $db_ch_ot = 64;

                $fin_id         = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $sec_code       = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $sch_no         = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $sec_sch        = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $dis_no         = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $dis_qty        = trim($allDataInSheet[$i][chr(++$db_ch_ot)]); 
                $bill_qty       = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);
                $bill_ref       = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);             
                $bill_dt        = trim($allDataInSheet[$i][chr(++$db_ch_ot)]);

                if(empty($bill_dt)){
                    $bill_dt = null;
                }else{
                    $dip_dt = date("Y-m-d",strtotime($bill_dt));                    
                }                

                $dt             = date('Y-m-d H:i:s');
                
                $insert_data = array(  
                    "fin_id_data"           => $fin_id,
                    "sec_code_data"         => $sec_code,
                    "sch_no_data"           => $sch_no,
                    "sec_sch_data"          => $sec_sch,
                    "dis_no_data"           => $dis_no,                   
                    "dis_qty_data"          => $dis_qty,                   
                    "bill_qty_data"         => $bill_qty,
                    "bill_ref_data"         => $bill_ref,                   
                    "bill_dt_data"          => $bill_dt,                    
                    "created_at_data"       => $dt,
                    "updated_at_data"       => $dt,           
                );
                
                if($this->srObject->insertSdisData($insert_data))
                {
                    ++$flag;
                }


            } //loop close  
        } else {
            $this->session->set_flashdata('error', 'Error. Invalid Excel Template');
            redirect(site_url('schill-bill-checking-suuti/sreco'));
        }  

        $this->session->set_flashdata('success', 'File Uploaded Successfully ..'.' New Record Inserted : '.$flag);
        redirect(site_url('schill-bill-checking-suuti/sreco'));

        
    }
    
}
0
-3
function trimArray(&$value) 
{ 
    $value = trim($value); 
}
$pmcArray = array('php ','mysql ', ' code ');
array_walk($pmcArray, 'trimArray');

by using array_walk function, we can remove space from array elements and elements return the result in same array.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.