sizeof的替代项,它忽略了对is_countable [duplicate]的检查

问题描述 投票:2回答:2

我想更新一个旧的PHP代码,其中对空数组使用了很多sizeof()函数,例如:

<?php
$a=array();
#...
if(sizeof($a['somthing_set_later'])>0){
 #...
}
$a['somthing_set_later']="something";

抛出:

sizeof():参数必须是实现Countable的数组或对象

为了解决这个问题,我最初可以用null填充这些数组,或者先检查is_countable(),但是我想在整个项目中使用find_and_replace代码,这很容易,如果有另一个函数不能抱怨。

是否有其他功能,不会在此代码上发出警告?


更新:最优将是速度的内置功能。

php
2个回答
1
投票

如果要使用一个函数来检查sizeof()并忽略不可数的参数,则可以在项目的标题中定义以下内容:

function countableSizeof($obj) {
  if(!is_countable($obj)) {
    return 0; //or a sentinel value of your choosing
  }
  return sizeof($obj);
}

0
投票

没有替代的内置函数,但是您可以重新创建确切的旧sizeof函数(这是别名vor count,在不对不可计数的参数发出警告的情况下用此代码作为替换:

if (!function_exists('is_countable')) {
    // < PHP 7.3 
    function is_countable($value)
    {
        return is_array($value) || $value instanceof Countable;
    }
}

/**
 * exact count() alternative, that doesn't throw an error if $array_or_countable is null
 * When the parameter is neither an array nor an object, 1 will be returned. There is one exception, if array_or_countable is NULL, 0 will be returned.
 * examples:
 *    "string": 1
 *    "": 1
 *    object: 1
 *    array(array()): 1
 *    array(): 0
 *    NULL: 0
 *    undefined: 0 (with Notice)
 * @param  object or array $array_or_countable
 * @param  const $mode COUNT_NORMAL (0) or COUNT_RECURSIVE (1) 
 * @return int
 */
function countValid($array_or_countable, $mode = COUNT_NORMAL)
{
    if (is_countable($array_or_countable)) {
        return count($array_or_countable, $mode);
    }

    return null === $array_or_countable ? 0 : 1;
}
© www.soinside.com 2019 - 2024. All rights reserved.