2017-10-11 39 views
0

我已經將複選框數據轉換爲一個字符串存儲在我的數據庫中。當我搜索in_array時,PHP爆炸函數只允許我檢測第一個數組項。爲什麼?

但是,當我嘗試使用爆炸函數將字符串轉換回數組時,我無法在in_array中搜索除第一項外的任何內容。爲什麼?

$rolepref = explode(',', $roles); 
print_r($rolepref) = [0] Strategy [1] Operations 
if (in_array("Strategy", $rolepref) { echo "yes" } => Will echo yes 
if (in_array("Operations", $rolepref) { echo "yes" } => Does not work 

我在這裏錯過了什麼?提前致謝!

+0

你可以發佈你想要檢查的實際數組嗎?和實際的代碼。看起來你剛剛輸入了它,因爲它沒有完成(在if語句中缺少右括號)。 –

回答

1

很可能你在爆炸數據後有空白。嘗試用裝飾

$roles = "Strategy, Operations"; 
$rolepref = array_map('trim', explode(',', $roles)); //trim and explode data 
if (in_array("Strategy", $rolepref)) { echo "yes"; } 
if (in_array("Operations", $rolepref)) { echo "yes"; } 
1

爆炸可能是您的$roles爲:"Strategy, Operations"當你explode它使用,它會給你兩個元素:"Strategy"" Operations" ...請注意這個詞之前的額外空間操作。因此在比較每個元素之前修剪空間。

$roles = "Strategy, Operations"; // lets say $rolepref = array_map('trim', explode(',', $roles)); if (in_array("Strategy", $rolepref)) { echo "yes"; } if (in_array("Operations", $rolepref)) { echo "yes"; }

0

如果發現有精確值in_array返回true。 這可能是你的陣列不完全相同,請嘗試用trim()清理它()

下面的代碼有效。

$array = [ 
    0 => 'Strategy', 
    1 => 'Operations', 
]; 

if (in_array("Strategy", $array)) 
{ 
    echo "yes s <br />"; 
} 

if (in_array("Operations", $array)) 
{ 
    echo "yes o <br />"; 
}