跳过数组键(如果已存在)

时间:2014-10-26 15:54:39

标签: php arrays key skip

我构建了一个这样的数组:

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

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

如您所见,foobar重复三次。我如何制作它,以便如果之前已经添加了数组则跳过该键?因此,在这种情况下,不应添加第二个和第三个foobar

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:3)

如果您想要“跳过”项目,则使用此方法。 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);