如何找到Array的大小

Saj*_*ood 26 php arrays if-statement counting

我想知道如何找到数组的大小,以及如何执行数组大小大于零的代码块?

if ($result > 0) {
    // Here is the code body which I want to execute
} 
else {
    // Here is some other code
}
Run Code Online (Sandbox Code Playgroud)

Dan*_*ani 31

你可以使用count()或sizeof()php函数

if (sizeof($result) > 0) {
    echo "array size is greater than zero";
}
else {
    echo "array size is zero";
}
Run Code Online (Sandbox Code Playgroud)

或者你可以使用

if (count($result) > 0) {
    echo "array size is greater than zero";
}
else {
    echo "array size is zero";
}
Run Code Online (Sandbox Code Playgroud)

我希望它会对你有所帮助

  • 仅当您将无效类型传递给 `count` 时才会抛出警告。请参阅此处的更改日志:http://php.net/manual/en/function.count.php。 (2认同)

May*_*eyz 14

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

int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
Run Code Online (Sandbox Code Playgroud)

计算数组中的所有元素,或对象中的某些元素.

例如:

<?php
    $a[0] = 1;
    $a[1] = 3;
    $a[2] = 5;
    $result = count($a);
    // $result == 3
Run Code Online (Sandbox Code Playgroud)

在你的情况下,它就像:

if (count($array) > 0)
{
    // Execute some block of code here
}
Run Code Online (Sandbox Code Playgroud)


rob*_*006 5

如果你只想检查数组是否不为空,你应该使用empty()- 它比 快得多count(),而且也更具可读性:

if (!empty($result)) {
    // ...
} else {
    // ...
}
Run Code Online (Sandbox Code Playgroud)