2011-09-06 156 views
0

我有一個字段,存儲標記逗號分離。我正在計算列出的項目數量。Count()返回1用逗號分隔的字符串與爆炸

比方說,我已經拉從數據庫中的數據,和$標籤變量具有以下信息:

$tags = "Videos,Magazines,Store"; 

// First separate tags by commas, put into into array 
$tagArray = explode(",",$tags); 

// Count how many items are in the array 
$arrayCount = count($tagArray); 

,它總是返回「1」,而不管是否有數組中的一個項目或不。 $ tags變量可以包含任意數量的項目 - 從空白到單個項目(如「視頻」)到多個項目「視頻,遊戲,商店」等。

有人可以幫我解決我在做什麼錯?

+6

返回'3' [我] (http://codepad.org/jHkGFYYW)。你是否[意外調用](http://codepad.org/GQnFA0NX)原始字符串上的'count()'? – alex

+1

不可複製。請發佈您的實際代碼。 (也許避免混合使用變量名稱。) – mario

+1

編碼問題?你的逗號不是逗號嗎? – deceze

回答

2

從PHP手冊:

如果delimiter包含未包含在字符串和一個負極限使用值,則空數組將被返回,否則包含字符串的數組將被返回。

所以,簡單地說 - 如果在字符串中沒有找到分隔符,那麼explode什麼也不做。如果您的變量包含空字符串,計數()將返回1 你需要NULL值計數()返回0。

試試這個:

$tags = "Videos,Magazines,Store"; 

// First separate tags by commas, put into into array<br> 
$tagArray = <b>($tags != '')?</b>explode(",",$tags)<b>:NULL</b>; 

// Count how many items are in the array<br> 
$arrayCount = count($tagArray);