remove entry from array with value = NULL
<blockquote>
  <p><strong>Possible Duplicate:</strong><br>
  <a href="http://stackoverflow.com/questions/2169669/remove-element-from-array-based-on-its-value">remove element from array based on its value?</a>  </p>
</blockquote>



<p>I have this array</p>

<pre><code>$arr = array(
 'key1'=&gt;'value1',
 'key2'=&gt;NULL,
 'key3'=&gt;'value2'
);
</code></pre>

<p>if I do <code>implode(',',$arr);</code> I get: <code>value1,,value2</code> (notice the empty space)</p>

<p>Is there a way to skip that NULL values? To get something like this: </p>

<p><code>value1,value2</code></p>

<p>I could traverse all the array and unset manually the key where the value is NULL, but it's a bit an overkill doens't it?</p>

<p>Edit:</p>

<p>To save time Maybe I could do just one loop to iterate over the array, and in the same loop I check for null values and if isn't null I append it the ','</p>

<p>like this:</p>

<pre><code>foreach($arr as $k=&gt;$v) {
  if ($v !== NULL) {
   echo $v.',';
  }
}
</code></pre>

<p>The problem here is that I have a final ',' at the end.</p>

<h2>Edit</h2>

<p>As gordon asked, it ran this test (1000000 iterations)</p>

<p>First using array_filter:</p>

<pre><code>$pairsCache = array('key1'=&gt;'value1','key2'=&gt;NULL,'key3'=&gt;'value3',
                    'key4'=&gt;'value4','key5'=&gt;'value5');

for($i=0;$i&lt;1000000;$i++) {

    $query = "INSERT INTO tbl (";
    $keys='';
    $values='';

    $pairs = array_filter($pairsCache,function($v){return $v !== NULL;});

    $keys = array_keys($pairs);

    //&gt; keys    
    $query .= implode(',',$keys ) . ") VALUES ( '";

    //&gt; values
    $query .= implode("','",$pairs) . "')";
}
</code></pre>

<p>Time: <strong>7.5949399471283</strong><br>
Query: "<code>INSERT INTO tbl (key1,key3,key4,key5) VALUES ( 'value1','value3','value4','value5')</code>"</p>

<p>Second using only one loop:</p>

<pre><code>for($i=0;$i&lt;1000000;$i++) {

    $query = "INSERT INTO tbl (";
    $keys='';
    $values='';

    foreach($pairsCache as $k=&gt;$v) {
        if ($v!==NULL) {

            $keys .= $k.',';
            $values .= "'{$v}',";
        }
     }

    $keys=rtrim($keys,',');
    $values=rtrim($values,',');

    $query = $query . $keys . ') VALUES ( ' . $values . ')';

 }
</code></pre>

<p>Time: <strong>4.1640941333771</strong><br>
Query: <code>INSERT INTO tbl (key1,key3,key4,key5,) VALUES ( 'value1','value3','value4','value5')</code></p>
