簡體   English   中英

如何檢查聲明數組是否為空?

[英]How do i check if a declare array is empty?

我有一個名為tagcat的數組,像這樣

$tagcat = array();

....
while ( $stmt->fetch() ) {
    $tagcat[$tagid] = array('tagname'=>$tagname, 'taghref'=>$taghref);
}

使用print_r($ tagcat)我得到以下結果集

   Array ( [] => Array ( [tagname] => [taghref] => ) )

使用var_dump($ tagcat),我得到

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

在PHP中,我想檢查數組是否為空。 但是當使用以下條件時,它總是在數組中找到東西,這是不正確的!

if ( isset($tagcat) ) {
    echo 'array is NOT empty';
} else {
    echo 'EMPTY!!!';
}

if ( !empty($tagcat) ) {
    echo 'array is NOT empty';
} else {
    echo 'EMPTY!!!';
}

如何檢查數組是否為空?

使用array_filter

if(!array_filter($array)) {
  echo "Array is empty";
}

這是為了檢查單個陣列。 對於您的多維數組。 我認為這應該工作:

$empty = 0;
foreach ($array as $val) {
  if(!array_filter($val)) {
    $empty = 1;
  }
}

if ($empty) {
  echo "Array is Empty";
}

如果沒有提供回調,則將刪除$ array等於FALSE的所有條目。

這樣,它僅返回不為空的值。 參閱docs示例中的更多信息示例#2沒有回調的array_filter()

如果需要檢查數組中是否有任何元素

if (!empty($tagcat) ) { //its $tagcat, not tagcat
    echo 'array is NOT empty';
} else {
    echo 'EMPTY!!!';
}

另外,如果您需要在檢查之前清空這些值

foreach ($tagcat as $cat => $value) {
    if (empty($value)) {
       unset($tagcat[$cat]);
    }
}
if (empty($tagcat)) {
   //empty array
}

希望能幫助到你

編輯:我看到你已經編輯了$ tagcat var。 因此,使用vardump($ tagcat)驗證您的結果。

if (empty($array)) {
 // array is empty.
 }

如果要刪除空元素,請嘗試以下操作:

foreach ($array as $key => $value) {
  if (empty($value)) {
     unset($array[$key]);
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM