I am trying to implode array with skipping specific value.
My array is:
$unit = array("123","56","0","1","10","965","65","0"," ","63");
From above array I don't want 0(zero) and blank value while imploding, I tried this:
$implode1 = implode(",", array_filter($unit));
Output : 123,56,1,10,965,65, ,63 (Skipping 0 but not blank value)
I tried callback method of array_filter
function
Below example, I tried to implode array and don't want 0, 1 and blank value
$implode1 = implode(",", array_filter($unit,function($v,$k){
return $v != " " || $v != '1' || $v != '0';
},ARRAY_FILTER_USE_BOTH));
output : 123,56,0,1,10,965,65,0, ,63
Can anyone help me Where am i wrong in both methods?
Use &&
instead of ||
:
$implode1 = implode(",", array_filter($unit,function($v,$k){
return $v != " " && $v != '1' && $v != '0';
},ARRAY_FILTER_USE_BOTH));
But in your case it's better to convert values to int and check:
$implode1 = implode(",", array_filter($unit,function($v,$k){
return (int)$v > 1;
},ARRAY_FILTER_USE_BOTH));
Here zeroes and empty values (which will be converted to zero) or even non-numeric values (which will be converted to zero also) will be skipped. And as you don't need 1
too I added greater than
check.
Also as you don't use $k
in your function - you can skip it and ARRAY_FILTER_USE_BOTH
parameter.