如何判断数组是否有一个或多个元素?
我需要执行一段代码,其中数组的大小大于零。
if ($result > 0) {
// Here is the code body which I want to execute
}
else {
// Here is some other code
}
如何判断数组是否有一个或多个元素?
我需要执行一段代码,其中数组的大小大于零。
if ($result > 0) {
// Here is the code body which I want to execute
}
else {
// Here is some other code
}
你可以使用 count()
或 sizeof()
PHP 函数:
if (sizeof($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
或者您可以使用:
if (count($result) > 0) {
echo "array size is greater than zero";
}
else {
echo "array size is zero";
}
count
传递无效类型时才会引发警告。请参阅此处的更改日志:http://php.net/manual/zh/function.count.php。 - Amadecount
— 统计数组中的所有元素或对象中某个元素的个数
int count ( mixed $array_or_countable [, int $mode = COUNT_NORMAL ] )
计算数组中的所有元素,或对象中的某些内容。
例如:
<?php
$a[0] = 1;
$a[1] = 3;
$a[2] = 5;
$result = count($a);
// $result == 3
根据您的情况,情况类似于:
if (count($array) > 0)
{
// Execute some block of code here
}
foreach($result as $key=>$value) {
echo $value;
}
如果您确定以下内容:
那么您不需要调用任何函数。 一个或多个元素的数组具有布尔值true
。没有元素的数组具有布尔值false
。
代码:(演示)
var_export((bool)[]);
echo "\n";
var_export((bool)['not empty']);
echo "\n";
var_export((bool)[0]);
echo "\n";
var_export((bool)[null]);
echo "\n";
var_export((bool)[false]);
echo "\n";
$noElements = [];
if ($noElements) {
echo 'not empty';
} else {
echo 'empty';
}
输出:
false
true
true
true
true
empty
<?php
$arr1 = array(1); // With one value which will give 1 count
$arr2 = array(); // With no value which will give 0 count
// Now I want that the array which has greater than 0 count should print other wise not so
if (count($arr1)) {
print_r($arr1);
}
else {
echo "Sorry, array1 has 0 count";
}
if (count($arr2)) {
print_r($arr2);
}
else {
echo "Sorry, array2 has 0 count";
}
//Array
$result = array(1,2,3,4);
//Count all the elements of an array or something of an object
if (count($result) > 0) {
print_r($result);
}
// Or
// Determines if a variable is empty
if (!empty($result)) {
print_r($result);
}
// Or
// sizeof - Alias of count ()
if (sizeof($result)) {
print_r($result);
}
<pre>
$ii = 1;
$arry_count = count($args);
foreach ( $args as $post)
{
if( $ii == $arry_count )
{
$last = 'blog_last_item';
}
echo $last;
$ii++;
}
</pre>
$last
是做什么用的? - Nico Haase