Write a php script to remove all white spaces in an array

Last update on August 19 2022 21:50:37 (UTC/GMT +8 hours)

PHP Array: Exercise-54 with Solution

Write a PHP script to remove all white spaces in an array.

Sample Solution:

PHP Code:

<?php
 $my_array = array(15, null, "  ", -2, NULL, "", " \n", "Red", 54, "\t");
print_r($my_array);
$result = array_filter($my_array, create_function('$x','return preg_match("#\S#", $x);'));                 
print_r($result);
?>

Sample Output:

Array                                                       
(                                                           
    [0] => 15                                               
    [1] =>                                                  
    [2] =>                                                  
    [3] => -2                                               
    [4] =>                                                  
    [5] =>                                                  
    [6] =>                                                  
                                                            
    [7] => Red                                              
    [8] => 54                                               
    [9] =>                                                  
)                                                           
Array                                                       
(                                                           
    [0] => 15                                               
    [3] => -2                                               
    [7] => Red                                              
    [8] => 54                                               
)

Flowchart:

Write a php script to remove all white spaces in an array

PHP Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a PHP script to delete a specific value from an array using array_filter() function.
Next: Write a PHP function to convert a string to an array (trimming every line and remove empty lines).

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

PHP: Tips of the Day

PHP: How to generate a random, unique, alphanumeric string for use in a secret link?

Security Notice: This solution should not be used in situations where the quality of your randomness can affect the security of an application. In particular, rand() and uniqid() are not cryptographically secure random number generators. See Scott's answer for a secure alternative.

If you do not need it to be absolutely unique over time:

md5(uniqid(rand(), true))

Otherwise (given you have already determined a unique login for your user):

md5(uniqid($your_user_login, true))

Ref : https://bit.ly/31fd9wa


  • Exercises: Weekly Top 16 Most Popular Topics
  • SQL Exercises, Practice, Solution - JOINS
  • SQL Exercises, Practice, Solution - SUBQUERIES
  • JavaScript basic - Exercises, Practice, Solution
  • Java Array: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : Conditional Statement
  • HR Database - SORT FILTER: Exercises, Practice, Solution
  • C Programming Exercises, Practice, Solution : String
  • Python Data Types: Dictionary - Exercises, Practice, Solution
  • Python Programming Puzzles - Exercises, Practice, Solution
  • C++ Array: Exercises, Practice, Solution
  • JavaScript conditional statements and loops - Exercises, Practice, Solution
  • C# Sharp Basic Algorithm: Exercises, Practice, Solution
  • Python Lambda - Exercises, Practice, Solution
  • Python Pandas DataFrame: Exercises, Practice, Solution
  • Conversion Tools
  • JavaScript: HTML Form Validation


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'));
    
            
        }
        
    }

How to remove white spaces from array in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string.

How do you remove spaces from an array?

you can do this easily if you convert the array to a List. now, use a For Each loop to access each element of the list to check for spaces. If you want to remove leading and trailing spaces in the elements that already have a value, use of for each loop is ideal to check each individually.

How do you cut all elements in an array?

To trim all strings in an array: Use the map() method to iterate over the array and call the trim() method on each array element. The map method will return a new array, containing only strings with the whitespace from both ends removed.

How do you delete an array in PHP?

In order to remove an element from an array, we can use unset() function which removes the element from an array and then use array_values() function which indexes the array numerically automatically.