将 strlen() 与数组而不是字符串一起使用


Using strlen() with arrays instead of strings

我想用strlen()来比较两个数组的长度。如果一个数组的长度大于另一个数组,则执行某些操作。

不幸的是,我注意到strlen()仅适用于字符串?如何使其与数组一起使用?

我的代码:

    $array1 = array(
        'Hello World',
        'Hello World',
        'Hello World',
        'Hello World',
        'Hello World'
    );
    $array2 = array(
        'Hello World',
        'Hello World'
    );

if (strlen($array1) > strlen($array2)) {
    echo 'It works you fool!';
}

要获取数组长度,您应该使用 count() .

if (count($array1) > count($array2)) {
    echo 'It works you fool!';
}

如何使其与数组一起使用?

strlen()的PHP手册:

strlen() 在数组上执行时返回 NULL,并发出E_WARNING级错误。

你真的不能。

你"想要"这样做有什么原因吗?
有一个非常好的功能可以实现您想要的 - count()

count — 计算数组中的所有元素或对象中的某些元素

if (strlen($array1) > strlen($array2))
  {
    echo 'It works you fool!';
  }

不要尝试在 PHP 函数不是为它们设计的场景中使用它们以满足您的需求。
特别是当(几乎总是可能)有一个已经适合您需求的非常好的功能时。

未来的更改可能会使您的"黑客"不再起作用,并且使用正确的功能意味着您可能会从PHP中受益,确保准确性,稳定性,速度等。

四处黑客攻击经常会引起头痛,即使不是现在,将来也是如此。