Home > Mobile >  Removing empty Array values
Removing empty Array values

Time:05-05

Good day!

I am trying to insert an array of locations to my database.

$locations = array();
$locations = $_POST['loc'];
$loc = implode(", ", $locations);

When the array gets inserted into my database, the array items that do not have value (which in this case are empty) still go through, even though those input fields were disabled:

Test, Test, Test, , , , , , , , , , , , , , ,

I've tried string_replace(), preg_replace(), array_splice() and unset() to remove the empty values.

I want to be able to insert an array to the database that does not take in the empty values. I've tested over and over to check the length of the array with count() and it returns the max of my array which is 18 even though I only wanted 3.

Am I missing something in my code? Is there a procedure that I'm not following? I hope I did my best to describe my issue and hope this will better improve my thought process and the way I handle code. Thank you all so much!

CodePudding user response:

The first 3 elements Test, Test, Test work as get imploded by , (, with space ).

Guessing there is yet another function that cover the implosion of the rest of elements (empty ones) that passing to the SQL statement. (, , , , , , , , , , , , , , ,)

CodePudding user response:

Solved!

I was able to remove the empty array values by using a PHP function called array_filter.

It now outputs:

Test, Test, Test

CodePudding user response:

this might work for you , it also can be done with array_filter, for specific array value use if;

<?php


$locations  = array("loc","","loc");
//above is example array; it can be $locations = $_POST['loc']; while using in program
            
            for($i = 0; $i < count($locations ); $i   )
            {
            
            
                            ///checking if array val is empty or single space 
                            if($locations [$i] == "" OR $locations [$i] == " " )
                            {
                            
                            //echo "empty position in ".$i;
                            
                            unset($locations [$i]); 
                            }

            }



$locations =array_values( $locations ); // restructuring array here

print_r($locations); // check if it is ok


//later implode your values


$loc = implode(", ", $locations);


?>
  • Related