2014-10-26 34 views
0

我創建數組是這樣的:跳過列鍵,如果它已經存在

$array = array(); // start with empty one 

$array[] = 'foobar'; 
$array[] = 'hello'; 
$array[] = 'foobar'; 
$array[] = 'world'; 
$array[] = 'foobar'; 

正如你所看到的,重複foobar三次。我如何做到這一點,以便數組跳過密鑰,如果它以前已被添加?所以在這種情況下,不應該添加第二個和第三個foobar

回答

3
<?php 

    $array = array(); // start with empty one 

    $array[] = 'foobar'; 
    $array[] = 'hello'; 
    $array[] = 'foobar'; 
    $array[] = 'world'; 
    $array[] = 'foobar'; 

    $array = array_unique($array); // removes all the duplicates 

    var_dump($array); 
?> 

From PHP Manual

+0

可愛,謝謝。我會的時候會接受這個。 – 2014-10-26 15:58:38

2

,如果你想 「跳過」 項目使用這種方式。 Demo

$array = array("hello", "world", "foobar"); 
$value1 = "foobar"; 
$value2 = "test"; 
if(!in_array($value1, $array)) $array[] = $value1; // this will not be added because foobar already exists in the array 
if(!in_array($value2, $array)) $array[] = $value2; // this will be added because it does not exist in the array 

如果你沒有一定要跳過的項目,只是想輸出,可以使用array_unique像這樣:Demo

$array = array("hello", "world", "foobar", "foobar"); 
$array = array_unique($array); 
相關問題