daG*_*vis 2 php arrays associative-array multidimensional-array
例如,我有一个这样的数组:
array(4)("a"=> string(0)"""b"=> string(0)"""c"=> string(0)"""d"=> string(0)"")
给定值都不应为空.
目前,我用这个:
if (!empty($_POST['x']['a']) && !empty($_POST['x']['b']) && !empty($_POST['x']['c']) && !empty($_POST['x']['d']))
Run Code Online (Sandbox Code Playgroud)
......从可读性方面来说很糟糕.
注意:数组是关联的.
count(array_filter($_POST['x'])) === 4
Run Code Online (Sandbox Code Playgroud)
一些解释:Empty()是布尔变量的相反,array_filter删除所有等于false的元素(即!empty()),此计数必须与4个元素的期望相匹配.
如果元素的数量由提交的元素总数(空或不)定义,则使用count()代替幻数:
if (count(array_filter($_POST['x'])) === count($_POST['x']))
{
echo 'No empty elements in $_POST["x"]!';
}
Run Code Online (Sandbox Code Playgroud)