php - in a foreach loop how to determine if the current key has a value set?
In an associative array in a foreach loop, I want to skip key -value pairs that have no value set. How can I do this? I tried like below, and similar using isset()
but it still adds the keys with empty values to the string.
foreach ($_POST as $param_name => $param_val) {
if (
!empty($param_val)
&& $param_name !== 'Last_Name'
&& $param_name !== 'First_Name'
&& $param_name !== 'Middle_Name'
&& $param_name !== 'Country'
&& $param_name !== 'Locality'
&& $param_name !== 'Fathers_Name'
&& $param_name !== 'Mothers_Name'
&& $param_name !== 'Birthdate'
) {
$classname = $param_name;
$pagestring = $pagestring."<h2>$param_name</h2><span id='$param_name' name='$param_name' class='$classname textstyle'>$param_val</span>";
} else {
$tags[] = $param_val;
$classname = $param_name."style"; $pagestring = $pagestring."<h2>$param_name</h2><div id='$param_name' name='$param_name' class='$classname textstyle'>$param_val</div>";
}
I do not want $param_name => $param_val
pairs that don't have a value posted to get added to $pagestring
Answer
Solution:
You can use array_filter
(https://www.php.net/manual/en/function.array-filter.php):
<?php
$arr = ['First_name' => 'foo', 'Last_name' => 'bar', 'empty_value' => ''];
print_r(array_filter($arr));
Output:
Array
(
[First_name] => foo
[Last_name] => bar
)
It will remove also false
, null
and 0
.
If you want to keep zeroes, use
array_filter($arr, 'strlen');
Source