Possible Duplicate:
remove element from array based on its value?
I have this array
$arr = array(
'key1'=>'value1',
'key2'=>NULL,
'key3'=>'value2'
);
if I do implode(',',$arr);
I get: value1,,value2
(notice the empty space)
Is there a way to skip that NULL values? To get something like this:
value1,value2
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?
Edit:
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 ','
like this:
foreach($arr as $k=>$v) {
if ($v !== NULL) {
echo $v.',';
}
}
The problem here is that I have a final ',' at the end.
As gordon asked, it ran this test (1000000 iterations)
First using array_filter:
$pairsCache = array('key1'=>'value1','key2'=>NULL,'key3'=>'value3',
'key4'=>'value4','key5'=>'value5');
for($i=0;$i<1000000;$i++) {
$query = "INSERT INTO tbl (";
$keys='';
$values='';
$pairs = array_filter($pairsCache,function($v){return $v !== NULL;});
$keys = array_keys($pairs);
//> keys
$query .= implode(',',$keys ) . ") VALUES ( '";
//> values
$query .= implode("','",$pairs) . "')";
}
Time: 7.5949399471283
Query: "INSERT INTO tbl (key1,key3,key4,key5) VALUES ( 'value1','value3','value4','value5')
"
Second using only one loop:
for($i=0;$i<1000000;$i++) {
$query = "INSERT INTO tbl (";
$keys='';
$values='';
foreach($pairsCache as $k=>$v) {
if ($v!==NULL) {
$keys .= $k.',';
$values .= "'{$v}',";
}
}
$keys=rtrim($keys,',');
$values=rtrim($values,',');
$query = $query . $keys . ') VALUES ( ' . $values . ')';
}
Time: 4.1640941333771
Query: INSERT INTO tbl (key1,key3,key4,key5,) VALUES ( 'value1','value3','value4','value5')
$arr = array_filter($arr);
array_filter()
removes every value, that evaluates to false
from $arr
.
If you need finer control, you can pass a callback as second argument
arr = array_filter($arr, function ($item) { return !is_null($item);});
At last of course you can iterate over the array yourself
foreach (array_keys($arr) $key) {
if (is_null($arr[$key])) unset($arr[$key]);
}
Note, that there is no downside, if you filter and output in two separate steps
You can use array_filter():
If no callback is supplied, all entries of input equal to FALSE (see converting to boolean) will be removed.
implode(',', array_filter($arr));
You can simply use bellow code.
Edited.
function nullFilter($val)
{
return $val !== NULL;
}
$arr = array( 'key1'=>'value1', 'key2'=>NULL, 'key3'=>'value2' );
$filteredArray = array_filter($arr,"nullFilter");
echo implode(',', $filteredArray);
Cheers!
Prasad.
There is no possibility to do this using only implode()
.
You can traverse all the array (as you said) maybe in a wrapper my_implode()
function, or you can use something less elegant such as:
trim(preg_replace('/[,]+/', ',', implode(',', $arr)), ',');