2017-05-23 102 views
1

試試這個代碼:爲什麼in_array()總是返回false?

您使用的URL與參數id e.g index.php?id=value將被推到該保持一個會話中data陣列。

我希望這個測試總能返回true。但它總是返回false,爲什麼?

if (in_array($id, $_SESSION['data'])) { 
     echo "$id in array"; 
    } else { 
     echo "$id not in array"; 
    } 

的完整代碼:

<?php 

    session_start(); 

    //uncomment when need to clear the data array. 
    //if (isset($_SESSION['data'])) { 
    // unset($_SESSION['data']); 
    // die; 
    //} 

    if (!isset($_SESSION['data'])) { 
     $_SESSION['data'] = []; 
    } 
    if (isset($_GET['id'])) { 
     $id = strval($_GET['id']); 

     if (!in_array($id, $_SESSION['data'])) { 
      $_SESSION['data'][$id] = "data_$id"; 
     } 

     echo '<pre>'; 
     print_r($_SESSION['data']); 
     echo '</pre>'; 

     // Why does this always return false? 
     if (in_array($id, $_SESSION['data'])) { 
      echo "$id in array"; 
     } else { 
      echo "$id not in array"; 
     } 
    }?> 
+2

'in_array'檢查值,而不是鍵。 –

+0

@JonStirling Opps ..然後我需要使用'array_key_exists'來代替 - 謝謝 –

回答

1

嘗試isset()函數功能。

實施例: -

if (isset($_SESSION['data'][$id])) { 
    echo "$id in array"; 
} else { 
    echo "$id not in array"; 
}