2014-10-26 30 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); 
相关问题