[英]Better way to check if all array values by key are empty?
I created function to check if all values for given key are empty. 我创建了函数来检查给定键的所有值是否为空。 It work fine but I would like to know if this function can be optimized or reduced ?
它工作正常,但我想知道是否可以优化或减少此功能?
function array_key_empty($array, $key)
{
if (is_array($array)) {
foreach ($array as $item) {
if (array_key_exists($key, $item)) {
if (!empty(trim($item[$key]))) {
return false;
}
}
}
}
return true;
}
Examples : 例子 :
$array = [
['code' => '', 'description' => 'Oh there is a beautiful product !', 'price' => 10],
['code' => '', 'description' => 'Another beautiful product', 'price' => 20],
['code' => '', 'description' => 'Hey where will you stop ?!', 'price' => 30]
];
array_key_empty($array, 'code'); // true because all code are empty
$array = [
['code' => 'Yup !', 'description' => 'Oh there is a beautiful product !', 'price' => 10],
['code' => '', 'description' => 'Another beautiful product', 'price' => 20],
['code' => '', 'description' => 'Hey where will you stop ?!', 'price' => 30]
];
array_key_empty($array, 'code'); // false because Yup...
You can do it like below:- 您可以像下面这样:
if(count(array_filter( array_map('trim',array_column($array,'code'))))==0){
echo "all values are empty";
}
Output:- https://eval.in/842810 输出: -https : //eval.in/842810
you can reduce your function to a single line like this : 您可以将功能简化为这样的一行:
<?php
$array = [
['code' => '', 'description' => 'Oh there is a beautiful product !', 'price' => 10],
['code' => '', 'description' => 'Another beautiful product', 'price' => 20],
['code' => '', 'description' => 'Hey where will you stop ?!', 'price' => 30]
];
function array_key_empty($array, $key)
{
return is_array($array) && empty(array_map('trim', array_filter(array_column($array, $key))));
}
echo "<pre>";
print_r(array_key_empty($array, 'code'));
output: 输出:
1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.