0

I want to remove the empty and null values from $listValues array. Here I am removed the empty values using array_filter. Sample Code:

$listValues = array("one", "two", "null","three","","four","null");
$resultValues = array_filter($listValues);

echo "<pre>";
print_r($resultValues);
echo "</pre>";

Result:

Array ( [0] => one [1] => two [2] => null [3] => three [5] => four [6] => null ) 

But I want

Array ( [0] => one [1] => two [3] => three [5] => four ) 

Any advice greatly appreciated.

4
  • 1
    Just apply an anonymous function to array_filter() to filter out what you want Commented Jan 14, 2016 at 4:38
  • I am edit my question Commented Jan 14, 2016 at 4:45
  • after array_filer just apply array_values Commented Jan 14, 2016 at 5:42
  • Show the array with null values Commented Jan 14, 2016 at 5:54

3 Answers 3

6

try this : use array_diff() function compares the values of two (or more) arrays, and returns the differences. to remove null and "" . if you need to remove some more field then add that values inside the array

<?php
$listValues = array("one", "two", "null","three","","four","null");
echo "<pre>";
$a=array_values(array_diff($listValues,array("null","")));
print_r($a);
echo "</pre>";
?>

output :

Array
(
    [0] => one
    [1] => two
    [2] => three
    [3] => four
)

refer http://www.w3schools.com/php/func_array_diff.asp

Sign up to request clarification or add additional context in comments.

Comments

1

Try array_filter with second parameter as a user defined function like this:

$listValues = array("one", "two", "null","three","","four","null");
print_r(array_filter($listValues, "filter"));
function filter($elmnt) {
    if ($elmnt != "null" && $elmnt != "" ) {
        return $elmnt;
    }
}

Comments

0

Use this code, First I corrected the index of an array, then unset null values from an array then corrected array indexes again:

$listValues = array("one", "two", "null","three","","four","null");
$listValues = array_values($listValues);
$temp = $listValues;

for($loop=0; $loop<count($listValues); $loop++){
    if($listValues[$loop] == "" || $listValues[$loop] == "null"){
        unset($temp[$loop]);
    }
}

$listValues = $temp;
$listValues = array_values($listValues);
echo "<pre>";
print_r($listValues);
echo "</pre>"; die;

But, if you want same indexes to get this output:

Array ( [0] => one [1] => two [3] => three [5] => four )

Then don't use this before <pre>:

$listValues = array_values($listValues);

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.