简体   繁体   English

PHP如何检查数组是否没有键和值

[英]PHP How to check if array has not key and value

I am using one custom CMS developed by someone and getting issue to check the array result. 我正在使用由某人开发的一个自定义CMS,但出现问题以检查阵列结果。

The function returns an array of username by passing userids array. 该函数通过传递userids数组来返回用户名数组。

Example Code 范例程式码

$all_users = "1,5,9,10,25,40"; // getting from database

$user_ids = explode(',', $all_users);
$usernames  = get_userids_to_usernames($user_ids); //this returns usernames array by passing uesrids array

If the database has not users in the column than the function is returning weird empty / null array as below. 如果数据库在该列中没有用户,则该函数将返回奇怪的空/空数组,如下所示。

var_dump($usernames); 后续代码var_dump($用户名);

array(1) { [""]=> NULL }

print_r($usernames); 的print_r($用户名);

(
    [] => 
)

Now issue is, I want to check if array is empty or has value in return but I have tried everything is_null , empty , count($usernames) > 0 but none of these working. 现在的问题是,我想检查数组是否为空或具有返回值,但是我尝试了所有方法is_nullemptycount($usernames) > 0但这些都不起作用。

Can anyone please help me to check conditionally if array has value or empty like above empty result. 任何人都可以请我有条件地帮助我检查数组是否有值或为空,如上述空结果。

Here is a workaround 这是一种解决方法

if (array_key_exists('', $a) && $a[''] === null) {
    unset($a['']);
}

then check on emptiness 然后检查空虚

You can use in_array to check if the array has an empty value and array_key_exists to check the key. 您可以使用in_array来检查数组是否为空值,并使用array_key_exists来检查键。

in_array("", $array)
array_key_exists("", $array)

http://php.net/manual/en/function.in-array.php http://php.net/manual/en/function.in-array.php

http://php.net/manual/fr/function.array-key-exists.php http://php.net/manual/fr/function.array-key-exists.php

Iterate through array, and check if keys or values are empty or null 遍历数组,并检查键或值是否为空或null

$newarray = [];
foreach($array as $key=>$value)
{
    if(is_null($value) || trim($value) == '' || is_null($value) || trim($key) == ''){
    continue; //skip the item
  }
        $newarray[$key] = $value;
}

If you want to use empty with it, try array filter 如果要使用空,请尝试使用数组过滤器

if (empty(array_filter($arr))) {
    //Do something
}

Array filter will automatically remove falsey values for you, and you can include a callback should you need more flexability. 数组过滤器将自动为您删除虚假值,并且如果需要更大的灵活性,则可以包括回调。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM