When doing a query in data bank I can receive both arrays as result:
Array
(
[] => 401
[BETA] => 223
[GAMMA] => 195
[DELTA] => 189
)
Array
(
[ALFA] => 294
[BETA] => 223
[GAMMA] => 195
[DELTA] => 189
)
What can I do to exclude the entirely line when the key is empty?
I tried something like this, but without success:
foreach($array as $key => $value){
if(array_key_exists($key, $value) && is_null($value[$key])) {
unset($key);
}
$array = $value;
}
Many thanks in advance!
Since the key is an empty string you could either remove that specific key:
$test = array(''=>'test', 'test'=>'test');
unset($test['']);
print_r($test);
Or remove all keys that contain only whitespace:
function array_remove_blank_keys($array) {
foreach ($array as $key => $value) {
if (preg_match('/^\s*$/', $key)) {
unset($array[$key]);
}
}
return $array;
}
$test = array(''=>'test', 'test'=>'test');
print_r($test);
print_r(array_remove_blank_keys($test));
Keys are never empty. They would have a numeric index. So just check to see if the key is numeric then unset.
foreach($array as $key => $value){
if(is_numeric($key)) {
unset($key);
}
}
and you don't need to do $array = $value;
The key is not null
, it is an empty string. eg:
$foo = array(""=>"bar");
print_r($foo);
Output:
Array
(
[] => bar
)
So you would want either empty($key)
or $key == ''
as your test, the difference being that empty()
can match quite a few things.
Use the empty($var)
function for evaluation. It considers these values empty and returns true if provided with one:
null
: the null value,
''
: empty string,
0
: numeric zero. Only if it is not assigned by direct or indirect assignment such as $var=0 or $var=1-1. Note that the zero string ('0'
) is not empty,
array()
: an empty array,
$var;
: an unassigned variable,
false
: value of false,
' '
: just a space string.