2013-07-31 52 views
-3

有關php代碼中in_array()的問題。我有以下陣列:in_array()期望參數2是數組,布爾值給定

Array (
    [0] => 11 
    [1] => 13 
    [2] => 14 
    [3] => 15 
    [4] => 16 
    [5] => 17 
    [6] => 18 
    [7] => 19 
    [8] => 20 
    [9] => 21 
    [10] => 22 
    [11] => 23 
    [12] => 24 
    [13] => 25 
    [14] => 26 
    [15] => 27 
    [16] => 28 
    [17] => 29 
) 

而下面的函數從該數組中的元素(因爲未設置不保留索引):

function removeFromArray($value, $array) { 
    // If value is in the array 
    if (in_array($value, $array)) { 
     // Get the key of the value 
     $key = array_search($value, $array); 
     // Remove the element 
     unset($array[$key]); 
     // Fix the key indexes 
     $array = array_values($array); 
     return $array; 
    } 
    return false; 
} 

不幸的是,我發現了錯誤:「in_array ()期望參數2是數組,布爾給定「當我做in_array($ value,$ array),如果條件。這發生在數組的任何元素上。

我用$ array變量檢查了is_array(),它返回true,所以變量被識別爲一個數組。有什麼想法嗎?

編輯:

我定義數組如下:

$array = array(11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29); 

並調用該函數是這樣的:(例如:如果我想刪除編號11)

$array= removeFromArray(11, $array); 
+0

請告訴我們你是如何調用函數和數組聲明的。 – vee

+0

最後添加了函數調用和數組定義。 – Inazuma

+0

使用保留關鍵字作爲變量是一種主要的編程錯誤。 – DevlshOne

回答

0

你的代碼很好。這不是一個答案,它只是表明你的代碼是好的。

我只是測試這個如下:

<?php 
function removeFromArray($value, $array) { 
    // If value is in the array 
    if (in_array($value, $array)) { 
     // Get the key of the value 
     $key = array_search($value, $array); 
     // Remove the element 
     unset($array[$key]); 
     // Fix the key indexes 
     $array = array_values($array); 
     return $array; 
    } 
    return false; 
} 

$array = array(11, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29); 
$array= removeFromArray(11, $array); 
var_dump($array); 

結果:

[[email protected]:/home/workspace/php/playground]$ php array_test.php 
array(17) { 
    [0] => 
    int(13) 
    [1] => 
    int(14) 
    [2] => 
    int(15) 
    [3] => 
    int(16) 
    [4] => 
    int(17) 
    [5] => 
    int(18) 
    [6] => 
    int(19) 
    [7] => 
    int(20) 
    [8] => 
    int(21) 
    [9] => 
    int(22) 
    [10] => 
    int(23) 
    [11] => 
    int(24) 
    [12] => 
    int(25) 
    [13] => 
    int(26) 
    [14] => 
    int(27) 
    [15] => 
    int(28) 
    [16] => 
    int(29) 
} 

而且PHP版本,雖然這不應該事:

[[email protected]:/home/workspace/php/playground]$ php -v 
PHP 5.4.16 (cli) (built: Jun 6 2013 09:20:50) 
Copyright (c) 1997-2013 The PHP Group 
Zend Engine v2.4.0, Copyright (c) 1998-2013 Zend Technologies 
    with Xdebug v2.2.3, Copyright (c) 2002-2013, by Derick Rethans 

所以,請檢查你有錯別字或什麼地方。

0

在調用removeFromArray($ value,$ array)時,如果$ array不是數組,那麼'in_array()期望參數2是數組'錯誤出現。

相關問題